Skip to content

Instantly share code, notes, and snippets.

@xinsight
Created February 5, 2013 21:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xinsight/4717701 to your computer and use it in GitHub Desktop.
Save xinsight/4717701 to your computer and use it in GitHub Desktop.
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