Home > DeveloperSection > Forums > filtering NSArray into a new NSArray in objective-c
Derek Honeybun
Derek Honeybun

Total Post:17

Posted on    August-22-2015 12:00 AM

 iPhone iPhone  Ios  Objective C 

 1 Reply(s)
 917  View(s)
Rate this:

I have an NSArray and I'd like to create a new NSArray with objects from the original array that meet certain criteria. The criteria is decided by a function that returns a BOOL. 

I can create an NSMutableArray, iterate through the source array and copy over the objects that the filter function accepts and then create an immutable version of it.

Is there a better way?

Tarun Kumar

Total Post:214

Posted on    August-22-2015 2:40 AM

NSArray and NSMutableArray provide methods to filter array contents. NSArray provides filteredArrayUsingPredicate: which returns a new array containing objects in the receiver that match the specified predicate. NSMutableArray adds filterUsingPredicate: which evaluates the receiver’s content against the specified predicate and leaves only objects that match. These methods are illustrated in the following example.

NSMutableArray *array = [NSMutableArray arrayWithObjects:@"Bill", @"Ben",

@"Chris", @"Melissa", nil];

NSPredicate *bPredicate = [NSPredicate predicateWithFormat:

@"SELF beginswith[c] 'b'"];

NSArray *beginWithB = [array filteredArrayUsingPredicate:bPredicate];

// beginWithB contains { @"Bill", @"Ben" }.

NSPredicate *sPredicate = [NSPredicate predicateWithFormat:

@"SELF contains[c] 's'"];

[array filterUsingPredicate:sPredicate];

// array now contains { @"Chris", @"Melissa" }

Modified On Aug-22-2015 02:44:31 AM

Don't want to miss updates? Please click the below button!

Follow MindStick