Skip to content

Instantly share code, notes, and snippets.

@azmfaridee
Created August 14, 2013 18:24
Show Gist options
  • Save azmfaridee/6233965 to your computer and use it in GitHub Desktop.
Save azmfaridee/6233965 to your computer and use it in GitHub Desktop.
Example of storing Objective-C blocks in an array. The example assumes ARC, no memory cleanup. Note that when adding the 'block' to the `NSMutableArray` you need to use the `copy` message (regardless of using ARC).
#import <Cocoa/Cocoa.h>
int main(int argc, char *argv[])
{
NSMutableArray *array = [NSMutableArray array];
for (int i = 0; i < 5; i++) {
[array addObject:[^() {
NSLog(@"I have Value of %d", i);
} copy]];
}
for (id (^fn)() in array) {
fn();
}
}
@theoknock
Copy link

Try using the second for loop in another method (after declaring the array as an object property, of course). While it's true you may have delayed the execution of the blocks until later in the method, if you want to execute them later from another method, you will not be able to do it with this solution. With this one, you may as well queue the blocks instead of adding them to an array.

This post has no value, save the proper way to extract blocks from an array.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment