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

我与影子孤独终老i 提交于 2019-12-18 19:39:46

问题


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?


回答1:


Short answer: NSArray:filteredArrayUsingPredicate:

Long answer: Predicate Programming Guide




回答2:


try something like this:

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



回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/2769110/how-to-quickly-search-an-array-of-objects-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!