1

I'm trying to understand how objective c blocks work.

As far as I understood: block is just a function with no name.

So for example:

 ^(int a, int b) { return a + b; }; 
  1. How can I invoke it?

  2. Can I use it multiple times as I would use a function? If I can then how?

  3. To what class will 'self' keyword refer to inside the block?

Any help is highly appreciated.

  • 2
    Have you read [*Blocks Programming Topics*](http://developer.apple.com/library/ios/#documentation/cocoa/Conceptual/Blocks/Articles/00_Introduction.html#//apple_ref/doc/uid/TP40007502-CH1-SW1)? It's chock-full of answers to questions like yours. – rob mayoff Jul 12 '13 at 18:56
  • 3
    What happened when you tried to answer these questions yourself? – jscs Jul 12 '13 at 18:57
  • 1
    Does it hurt when you use Google? – Rob van der Veer Jul 12 '13 at 21:25

1 Answers1

3
- (void)something
{
    void (^ sample)(void) = ^{
        NSLog(@"I am %@", self);
    };

    sample();
    sample();
}

...or more in keeping with your sample:

int (^ adder)(int a, int b) = ^(int a, int b) { return a + b; };
NSLog(@"Result: %d", adder(5, adder(5, 4)));
Phillip Mills
  • 30,888
  • 4
  • 42
  • 57