Skip to content

Instantly share code, notes, and snippets.

@cmittendorf
Last active December 17, 2015 04:49
Show Gist options
  • Save cmittendorf/5553727 to your computer and use it in GitHub Desktop.
Save cmittendorf/5553727 to your computer and use it in GitHub Desktop.
With this objective-c category you can put blocks into an array and execute them one by one.
/**
* cc -Wall -fno-objc-arc -framework Foundation -o array_of_blocks array_of_blocks.mm
* Based on http://orangejuiceliberationfront.com/blocks-and-block-lists/ from Uli Kusterer
*/
#import <Foundation/Foundation.h>
@interface NSMutableArray (BlocksArray)
- (void)startExecutingBlocks;
- (void)executeNextBlock;
@end
@implementation NSMutableArray (BlocksArray)
- (void)addBlock:(void (^)())aBlock
{
[self addObject:[^(NSMutableArray *steps) {
aBlock();
[self executeNextBlock];
} copy]];
}
- (void)startExecutingBlocks
{
if ([self count] > 0) {
void *(^block)(NSMutableArray *array) = self[0];
block(self);
}
}
- (void)executeNextBlock
{
[self removeObjectAtIndex:0];
if ([self count] > 0) {
void *(^block)(NSMutableArray *array) = self[0];
block(self);
}
}
@end
int main(int argc, char **argv)
{
@autoreleasepool {
NSMutableArray *blockSteps = [NSMutableArray array];
[blockSteps addBlock:^{ NSLog(@"Step 1"); }];
[blockSteps addBlock:^{ NSLog(@"Step 2"); }];
[blockSteps addBlock:^{ NSLog(@"Step 3"); }];
[blockSteps addBlock:^{ NSLog(@"Step 4"); }];
[blockSteps startExecutingBlocks];
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment