搜索对象的NSArray以匹配任何属性的String

use*_*895 3 objective-c ios

我有一个NSArray对象,这些对象有10个属性.我想对这些对象进行文本搜索.

我知道如何一次搜索1个属性,但有一种简单的方法可以一次搜索所有属性吗?

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

@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;
Run Code Online (Sandbox Code Playgroud)

如果我搜索"医生",我希望看到所有结果,其中一个或多个这些属性中有"医生"一词.例如,如果1个对象的类别为"doctor",而另一个对象的电子邮件地址为"smith@doctorsamerica.com",则它们都应显示在结果中.

Kyl*_*e C 14

 NSString *searchTerm = @"search this";
 NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF LIKE[cd] %@", searchTerm];
 NSArray *filtered = [array filteredArrayUsingPredicate:predicate];
Run Code Online (Sandbox Code Playgroud)

如果存在特定属性,则可以将谓词更改为:

 NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.propertyName LIKE[cd] %@", searchTerm];
Run Code Online (Sandbox Code Playgroud)

要搜索所有属性,您必须使用逻辑运算符将它们绑定在一起

  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];
Run Code Online (Sandbox Code Playgroud)