搜索对象的NSArray以匹配任何属性的String [英] Search NSArray of objects for String matching any property
问题描述
我有一个NSArray对象,这些对象有10个属性。我想对这些对象进行文本搜索。
I have an NSArray of objects, and those objects have 10 properties. I would like to do a text search of those objects.
我知道如何一次搜索1个属性,但有一种简单的方法可以一次搜索所有属性?
I know how to search 1 property at a time, but is there an easy way to search ALL properties at once?
以下是我的对象拥有的属性列表:
Here is a list of properties that my objects have:
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSString * phone;
@property (nonatomic, retain) NSString * secondaryPhone;
@property (nonatomic, retain) NSString * address;
@property (nonatomic, retain) NSString * email;
@property (nonatomic, retain) NSString * url;
@property (nonatomic, retain) NSString * category;
@property (nonatomic, retain) NSString * specialty;
@property (nonatomic, retain) NSString * notes;
@property (nonatomic, retain) NSString * guid;
如果我搜索医生,我希望看到所有结果中的一个或多个属性中有医生这个词。例如,如果1个对象的类别为doctor,而另一个对象的电子邮件地址为smith@doctorsamerica.com,则它们都应显示在结果中。
If I search for "doctor", I would like to see all results where 1 or more of these properties has the word "doctor" in it. For example, if 1 object has a category of "doctor", and another object has an email address of "smith@doctorsamerica.com", they should both show up in the results.
推荐答案
NSString *searchTerm = @"search this";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF LIKE[cd] %@", searchTerm];
NSArray *filtered = [array filteredArrayUsingPredicate:predicate];
如果有特定属性,您可以将谓词更改为:
If there is a specific property you can change the predicate to:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.propertyName LIKE[cd] %@", searchTerm];
要搜索所有属性,您必须将它们与逻辑运算符绑定在一起
To search all properties, you will have to bind them together with a logical operator
NSString *query = @"blah";
NSPredicate *predicateName = [NSPredicate predicateWithFormat:@"name contains[cd] %@", query];
NSPredicate *predicatePhone = [NSPredicate predicateWithFormat:@"phone contains[cd] %@", query];
NSPredicate *predicateSecondaryPhone = [NSPredicate predicateWithFormat:@"secondaryPhone contains[cd] %@", query];
NSArray *subPredicates = [NSArray arrayWithObjects:predicateName, predicatePhone, predicateSecondaryPhone, nil];
NSCompoundPredicate *predicate = [NSCompoundPredicate orPredicateWithSubpredicates:subPredicates];
这篇关于搜索对象的NSArray以匹配任何属性的String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!