0

For example I have a simple block of C# codes:

IList<string> list = new List<string>();
list.Add("Objective-C");
list.Add("C#");
list.Add("C++");
list.Add("Java");
list.Add("Python");

var filteredList = list.Where(c => c.Contains("C")).ToList<string>();

The filteredList will only contain "Objective-C", "C#", and "C++".

I would like to know if Objective-C supports any method to filter the list of objects (NSArray) using lambda like this? Thanks.

chris
  • 55,166
  • 13
  • 130
  • 185
Johnny Bui
  • 193
  • 1
  • 8

2 Answers2

2

NSSet has objectsPassingTest:

NSSet *set = [NSSet setWithArray:@[@"C#", @"Objective-C", @"Ruby"]];
NSSet *cSet = [set objectsPassingTest:^BOOL(NSString *language, BOOL *stop) {
    return [language rangeOfString:@"C"].location != NSNotFound;
}];
NSLog(@"%@", cSet);

To make the example easier, this code assumes that the set has only NSString objects.

For NSArrays you can use indexesOfObjectsPassingTest:.

Sebastian
  • 7,500
  • 5
  • 32
  • 48
0

NSPredicates are generally used to sort and filter through collections.

NSArray *array = @[@"Objective-C", @"C#", @"C++", @"Java", @"Python"];
NSPredicate *p = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
    return [((NSString *)evaluatedObject) rangeOfString:@"C"].location != NSNotFound;
}];
NSArray *result = [array filteredArrayUsingPredicate:p];

These predicates are usually made with format strings instead of blocks, since these queries can handle most situations, but blocks are available as shown.

For more reading on NSPredicates: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Predicates/predicates.html#//apple_ref/doc/uid/TP40001789

sbrun
  • 177
  • 1
  • 13