NSArray category that extends it with abilities inspired by Microsoft LINQ
These methods allow you to:
- Take a subset of an array
- Take all the elements in an array that are of a certain class
- Get a singular item/property off each object in an array
- Get a subset (stored in a dictionary) of items off each object in an array
- Get the first object in an array that matches a predicate, or
nil
if none found. - Get the last object in an array that matches a predicate, or
nil
if none found.
A couple examples:
NSArray *array = @[ @"Casey", @"Erin", @"Chris" ];
NSString *firstC = [array firstOrNil:[NSPredicate predicateWithFormat:@"SELF BEGINSWITH \"C\""]]; // firstC = @"Casey"
NSString *lastC = [array lastOrNil:[NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
return [[evaluatedObject substringToIndex:1] isEqualToString:@"C"];
}]]; // lastC = @"Chris". This could have been done using the same predicate as firstC; just showing another approach.
NSArray *selections = [array select:^id(id source) {
return [source uppercaseString];
}]; // selections = @[ @"CASEY", @"ERIN", @"CHRIS" ]
arr = @[ @"Casey", @30, @"Erin", @29, @"Adam", @26 ];
NSArray *strings = [arr ofClass:[NSString class]]; // Strings = @[ @"Casey", @"Erin", @"Adam" ]
NSArray *numbers = [arr ofClass:[NSNumber class]]; // Numbers = @[ @30, @29, @26 ]
arr = // Some array of NSAttributedStrings
NSArray *values = [arr valueForKeys:@[ @"string", @"length" ]]
// values = @[ @{ @"length" : 5, @"string" : @"Casey" },
// @{ @"length" : 4, @"string" : @"Erin", },
// @{ @"length" : 5, @"string" : @"Chris" } ]