Created
January 15, 2011 21:50
-
-
Save mikelikespie/781298 to your computer and use it in GitHub Desktop.
Some fun stuff for enumerating
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
@interface NSArray (EnumerableStuff) | |
/** | |
* similar to a map | |
*/ | |
- (NSArray *) objectsTransformedByBlock:(id (^)(id, NSUInteger, BOOL *))block; | |
/** | |
* filter the array | |
*/ | |
- (NSArray *) objectsPassingTest:(BOOL (^)(id, NSUInteger, BOOL *))predicate; | |
/** | |
* takes the return value of the block as the key and maps it to the object for it | |
*/ | |
- (NSDictionary *) dictionaryOfObjectsWithKeyBlock:(id (^)(id, NSUInteger, BOOL *))block; | |
@end |
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
#import "NSArray+enumerableStuff.h" | |
@implementation NSArray (EnumerableStuff) | |
- (NSArray *) objectsTransformedByBlock:(id (^)(id, NSUInteger, BOOL *))block { | |
NSMutableArray *ret = [NSMutableArray arrayWithCapacity:[self count]]; | |
[self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { | |
[ret addObject:block(obj, idx, stop)]; | |
}]; | |
return ret; | |
} | |
- (NSArray *) objectsPassingTest:(BOOL (^)(id, NSUInteger, BOOL *))predicate { | |
return [self objectsAtIndexes:[self indexesOfObjectsPassingTest:predicate]]; | |
} | |
- (NSDictionary *) dictionaryOfObjectsWithKeyBlock:(id (^)(id, NSUInteger, BOOL *))block { | |
NSArray *keys = [self objectsTransformedByBlock:block]; | |
return [NSDictionary dictionaryWithObjects:self forKeys:keys]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment