Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to quickly search an array of objects in Objective-C

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?

like image 337
randombits Avatar asked May 04 '10 21:05

randombits


4 Answers

try something like this:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"firstName==%@ OR lastName==%@",@"Ken",@"Ken"];
NSArray *results = [allPersons filteredArrayUsingPredicate:predicate];
like image 100
gSorry Avatar answered Oct 21 '22 15:10

gSorry


Short answer: NSArray:filteredArrayUsingPredicate:

Long answer: Predicate Programming Guide

like image 31
Jaanus Avatar answered Oct 21 '22 14:10

Jaanus


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"
                                                 ascending:YES];
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.

like image 22
Hemant Sharma Avatar answered Oct 21 '22 13:10

Hemant Sharma


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

like image 38
progrmr Avatar answered Oct 21 '22 15:10

progrmr