Search code examples
objective-cxcodefunctionlambdaobjective-c-blocks

Blocks and Objects in Objective-C


I've started learning how to use blocks/functions/lambda in Objective-C. But I can't get it to work with Objects. Probably I'm missing some pointer, but it's not working however I do. This is my code for the moment:

MyEventArgs (^skapaEventArg)(Operation); 
skapaEventArg = ^(Operation a) { return *[[MyEventArgs alloc] initWithOperation:a]; };
MyEventArgs *a = skapaEventArg(Add);

But I get the error that this pic shows:

If I do

MyEventArgs a = skapaEventArg(Add);

to put it on the stack, Xcode gives me the usual "Interface cannot be statically allocated"-error

How do I get this simple code to work, using blocks?


Solution

  • It should be:

    MyEventArgs *(^skapaEventArg)(Operation); 
    skapaEventArg = ^(Operation a) { return [[MyEventArgs alloc] initWithOperation:a]; };
    MyEventArgs *a = skapaEventArg(Add);
    

    Note the * in the first line, and the lack of it in the second line.