在对象的 NSArray 中搜索与任何属性匹配的字符串

2024-05-24

我有一个 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;

如果我搜索“医生”,我希望查看其中 1 个或多个属性中包含“医生”一词的所有结果。例如,如果 1 个对象的类别为“医生”,而另一个对象的电子邮件地址为“smit[电子邮件受保护] /cdn-cgi/l/email-protection”,它们都应该出现在结果中。


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

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

  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];
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在对象的 NSArray 中搜索与任何属性匹配的字符串 的相关文章

随机推荐