【问题标题】:Filter array in ios checking multiple propertiesios中的过滤器数组检查多个属性
【发布时间】:2013-03-23 04:01:44
【问题描述】:

我有一组自定义对象。自定义对象如下所示

@interface User : NSObject
@property(nonatomic, strong)NSString *user_Id;
@property(nonatomic, strong)NSString *user_Name;
@property(nonatomic, strong)NSString *user_UserName;
@end

我必须过滤检查 2 个属性的数组。也就是说,如果我搜索 a,那么它应该从包含 a 的数组中过滤出的用户列表,其中包含 user_Nameuser_Id 。我怎样才能做到这一点?对于我知道的单个属性[user_Name]

NSString *predicateString = @"user_Name MATCHES[c] %@";
NSString *matchString =  [NSString stringWithFormat: @".*%@.*",searchText];
NSPredicate *predicate =[NSPredicate predicateWithFormat:predicateString, matchString];
self.searchResults = [userArray filteredArrayUsingPredicate:predicate];

【问题讨论】:

  • 使用其中两个并合并结果怎么样?
  • true.but如何合并结果而不重复?
  • 因为 user_Id 很常见,遍历其中一个,如果 user_id 不在数组中,则添加它。
  • 我刚刚找到了一个直接的解决方案.. 发布它。
  • 哎呀我没找到..无论如何我得到了我想要的东西谢谢大家:)

标签: iphone ios search uisearchbar nspredicate


【解决方案1】:

You can join predicate conditions with OR,如:

NSString *predicateString = @"(user_Name MATCHES[c] %@) OR (user_Id MATCHES[c] %@)";

或者,您可以使用indexesOfObjectsPassingTest: 和适当的测试块过滤数组,然后使用objectsAtIndexes: 来获取通过测试的对象数组。

【讨论】:

  • 由于某种原因这对我不起作用,所以使用 orCompoundQueries 并且它起作用了。
【解决方案2】:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(user_Name== %@) || (user_Id== %@), <name>,  <id>];

【讨论】:

    【解决方案3】:

    尝试使用这个谓词字符串

    NSString *predicateString = @"user_Name MATCHES[c] %@ OR user_Id MATCHES[c] %@";
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-02
      • 2019-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多