Created
June 7, 2021 14:06
-
-
Save theoknock/2cb68efbf899773a274f2b7d7392f66a to your computer and use it in GitHub Desktop.
Adding blocks with persistent arguments to an array
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
// 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