Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
List Comprehension
NSArray *a = @[@"Hello", @"Will This work?", @"can it work?", @"Yes!"];
// sure, this works...
NSMutableArray *b = [NSMutableArray arrayWithCapacity:[a count]];
[a enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
[b insertObject: [obj uppercaseString] atIndex: idx];
}];
// but it assumes that the enumeration is always increasing
// you can't go through the array backwards (or concurrently)
[a enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[b insertObject:[obj uppercaseString] atIndex:idx]; // crash!
}];
// why not just a simple for loop? It's also the fastest...
NSMutableArray * b = [NSMutableArray arrayWithCapacity:[a count]];
for (id item in a) {
[b addObject:[item uppercaseString]];
}
// or even edit the array in-place?*
NSMutableArray *b = [NSMutableArray arrayWithArray:a];
for (__strong id item in b) { // __strong is for ARC
item = [item uppercaseString];
}
// * only works for NSStrings, not NSNumbers. No idea why!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.