3

I am trying to create a block in Objective-C, at runtime, from a char *string. But I can't find the way to do it.

I think that the dynamic nature of Objective-C would allow to do something like

char *blockString = "^(int a, int b) {return a + b;};";
printf("%s\n", blockString);
int (^addBlock)(int a, int b) = (^)*blockString;
int result = addBlock(3, 6);

Obviously, the syntax of the third line is too wacky for the compiler to process, but I hope it gives you the idea of what I want to accomplish.

Is this possible?

2
  • 1
    You want to parse block literals into blocks... This is not going to end well. Commented May 17, 2014 at 0:23
  • 1
    Why would you have these strings? Where would you get them from? Commented May 17, 2014 at 21:21

1 Answer 1

8

No. Objective C is a compiled language, not interpreted.

Sign up to request clarification or add additional context in comments.

4 Comments

Though there are several ways to execute code dynamically at runtime using things like performSelector and NSSelectorFromString as well as various Objective-C runtime functions and NSInvocation.
Thx @Duncan C. I understand that part, but given that we can create/define classes dynamically at runtime, I was wondering if we could create a block (that is some sort of object) at runtime.
@eharo2 The difference is that when we're dynamically altering/creating classes at run-time, we're not trying to compile code, just rearranging pointers to existing compiled code. What you're trying to do is to dynamically compile code, which is neither supported, nor allowed.
As david says, it's nether supported nor allowed, but with additional support from Apple it might be possible. LLVM now does on-the-fly compilation as part of the LLDB debugger. However, that's on a Mac with Xcode installed. The comelier is not present on iOS devices. It would be a major effort to port the compiler to iOS, and to allow just-in-time compilation. Apple has always banned the use of dynamically executed code like ActionScript, Java, etc as a matter of policy, so I think it VERY unlikely that they would commit the effort needed to make this possible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.