2

I was under the assumption that Objective-C's Blocks where just regular Cocoa objects. However, I found out, in the worst possible way, that there's slight difference: calling a nil block is not as innocuous as sending a message to nil.

This code crashes:

-(void) nilBlock{

    void (^thunk)(void) = ^void(void) {
        NSLog(@"Help me, I am blocked!");
    };

    NSLog(@"%@\n%@", [thunk class], thunk);

    thunk();
    thunk = nil;
    thunk();        // Bad access error

}

I thought that when you run a block, you're just sending some message to it and was expecting the last line to be a NOP.

What exactly is going on when you run a block?

Is there a way to avoid having to check if the block variable is nil (this seems like a flashback to Java...)?

cfischer
  • 24,452
  • 37
  • 131
  • 214
  • Most languages take exception to dereferencing nil/null/NULL/0/nullptr, not just Java. – trojanfoe Mar 05 '14 at 10:41
  • But @trojanfoe, you know Objective-C *usually* doesn't. – James Webster Mar 05 '14 at 10:48
  • Only in one particular case: sending a message to an Objective-C object. Try setting-up a function pointer to `NULL` and you'll get th e same results (function pointers being C-language, not Objective-C, just like blocks is a C-language feature). – trojanfoe Mar 05 '14 at 10:50

0 Answers0