Created
August 14, 2013 18:24
-
-
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).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.