Friday, November 22, 2013

iOS: Anonymous Blocks As Method Parameters

Every time I want to write a method that takes a simple block as a parameter, I have to do a google search to get the correct syntax. So I'm putting it here so I'll know where to look next time! Here's an example:
- (void)someMethodWithBoringParameter:(NSInteger)boring
    excitingBlockParameter:(void(^)())callback;
You then call the method like so:
[self someMethodWithBoringParameter:99 excitingBlockParameter:^{
    //
    // Do something funky
    //
}];
Just for completeness, here's how to declare the block as a variable:
void(^excitingBlock)() = ^{
    // Code
};

No comments:

Post a Comment