Created
February 5, 2013 21:12
-
-
Save xinsight/4717701 to your computer and use it in GitHub Desktop.
List Comprehension
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 *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