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?
try something like this:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"firstName==%@ OR lastName==%@",@"Ken",@"Ken"];
NSArray *results = [allPersons filteredArrayUsingPredicate:predicate];
Short answer: NSArray:filteredArrayUsingPredicate:
Long answer: Predicate Programming Guide
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.
You'll have to do a linear search, comparing each entry in the array to see if it matches what you're looking for.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With