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...)?