Skip to content

Instantly share code, notes, and snippets.

@phildow
Last active December 14, 2015 16:59
Show Gist options
  • Save phildow/5118857 to your computer and use it in GitHub Desktop.
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.
// 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