search对象的NSArray以匹配任何属性的string

我有一个NSArray的对象,这些对象有10个属性。 我想对这些对象进行文本search。

我知道如何一次search一个属性,但有没有简单的方法来一次search所有属性?

以下是我的对象具有的属性列表:

@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; 

如果我search“医生”,我希望看到所有这些属性中有一个或多个属性中包含“医生”字样的结果。 例如,如果1个对象具有“医生”类别,而另一个对象具有“smith@doctorsamerica.com”的电子邮件地址,则它们都应显示在结果中。

  NSString *searchTerm = @"search this"; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF LIKE[cd] %@", searchTerm]; NSArray *filtered = [array filteredArrayUsingPredicate:predicate]; 

如果有一个特定的属性,你可以改变谓词为:

  NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.propertyName LIKE[cd] %@", searchTerm]; 

要search所有属性,您必须将它们与逻辑运算符绑定在一起

  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]; 

将一个matches:方法添加到你的类中:

 - (BOOL)matches:(NSString *)term { if ([self.name rangeOfString:term options:NSCaseInsensitiveSearch| NSDiacriticInsensitiveSearch].location != NSNotFound) { return YES; } else if ([self.phone rangeOfString:term options:NSCaseInsensitiveSearch| NSDiacriticInsensitiveSearch].location != NSNotFound) { return YES; } else if (...) { // repeat for all of the properties return YES; } return NO; } 

现在你可以遍历你的对象检查每一个:

 NSArray *peopleArray = ... // the array of objects NSString *someTerm = ... // the search term NSMutableArray *matches = [NSMutableArray array]; for (id person in peopleArray) { if ([person matches:someTerm]) { [matches addObject:person]; } } 

而不是单独硬编码每个属性名称,你可以得到一个类的属性名称的数组: Objective-C中的类属性列表 (假设它们都是string,或者你可以检查每个属性的types是否为NSString类,米不知道如何做到这一点)

然后在每个要search的对象上,可以遍历每个对象的属性并检查每个对象的值:

 id objectValue = [object valueForKey:[NSString stringWithUTF8String:propertyName]]; // let's say the property is a string NSString *objectValueString = (NSString *)objectValue; 

然后你可以检查一下属性是否与你的searchTerm匹配:

 BOOL propertyValueMatchesSearchTerm = [objectValueString rangeOfString:mySearchTermString].location != NSNotFound; if (propertyValueMatchesSearchTerm) { // add object to search results array }