Take the 2-minute tour ×

Is there a way in Objective-C to search an array of objects by the contained object's properties if the properties are of type string?

For instance, I have an NSArray of Person objects. Person has two properties, NSString *firstName and NSString *lastName.

What's the best way to search through the array to find everyone who matches 'Ken' anywhere in the firstName OR lastName properties?

share|improve this question

4 Answers 4

up vote 14 down vote accepted

Short answer: NSArray:filteredArrayUsingPredicate:

Long answer: Predicate Programming Guide

share|improve this answer
I like your answer better than mine. –  progrmr May 4 '10 at 22:50
That worked GREAT for me. Thanks! –  randombits May 4 '10 at 23:54

try something like this:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"firstName==%@ OR lastName==%@",@"Ken",@"Ken"];
NSArray *results = [allPersons filteredArrayUsingPredicate:predicate];
share|improve this answer

You'll have to do a linear search, comparing each entry in the array to see if it matches what you're looking for.

share|improve this answer

You can simply use NSPredicate to filter your search from actual result array:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.property_name contains[c] %@",stringToSearch];
filteredPendingList = [NSMutableArray arrayWithArray:[mainArr filteredArrayUsingPredicate:predicate]];
NSSortDescriptor *sortDescriptor;
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"property_name"
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray;
sortedArray = [filteredPendingList sortedArrayUsingDescriptors:sortDescriptors];

So you will be getting the sorted array with filtered result. property_name above is the name of variable inside your object on which you want to perform your search operation. Hope it will help you.

share|improve this answer

Your Answer


