Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save theoknock/2cb68efbf899773a274f2b7d7392f66a to your computer and use it in GitHub Desktop.
Save theoknock/2cb68efbf899773a274f2b7d7392f66a to your computer and use it in GitHub Desktop.
Adding blocks with persistent arguments to an array
// This is similar to using callback blocks with three key differences:
// 1. Blocks stored in an array retain their arguments outside of the context in whicn they were created
// 2. Blocks can be called in combination or in a variance of succession
// 3. The number of blocks to be executed is known up-front
// The same effect could be achieved via regular callback blocks; however, the argument values would not be persistent
typedef int(^BlockObject)(void);
- (void)test {
NSMutableArray <BlockObject> * blockArray;
blockArray = [[NSMutableArray alloc] initWithCapacity:3];
int numbers[3] = {1, 2, 3};
[self addBlocksWithArguments:numbers toArray:blockArray];
[self executeBlocks:blockArray];
}
- (BlockObject)blockWithArgument:(int)number {
return [^ int {
printf("Input\t%d\n", number);
return number;
} copy];
}
- (void)addBlocksWithArguments:(int[3])numbers toArray:(NSMutableArray <CallbackBlock> *)array {
for (int i = 0; i < 3; i++)
[array addObject:[self blockWithArgument:i]];
}
- (void)executeBlocks:(NSMutableArray <CallbackBlock> *)array {
for (int i = 0; i < 3; i++) {
CallbackBlock cb = [array objectAtIndex:i];
printf("Output\t%d\n", cb());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment