Last active
December 14, 2015 16:59
-
-
Save phildow/5118857 to your computer and use it in GitHub Desktop.
Initializing an NSArray with a block that is called for each element, allowing the array elements to initialize themselves as the array is built.
This file contains 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
// NSArray+BlocksInit.h | |
- (id) initWithCount:(NSUInteger)count block:(id(^)(NSUInteger index))block | |
{ | |
NSMutableArray *array = [[NSMutableArray alloc] init]; | |
for ( NSUInteger i = 0; i < count; i++ ) { | |
id element = block(i); | |
if (element) [array addObject:element]; | |
} | |
return [array copy]; | |
} | |
// Usage | |
// Create an array of numbers 0-9 | |
NSArray *modelArray = [[NSArray alloc] initWithCount:10 block:^id(NSUInteger index) { | |
return [NSNumber numberWithInteger:index]; | |
}]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment