【问题标题】:Can I apply multiple predicates to an NSFetchRequest? Would it be better to manually parse my results?我可以对 NSFetchRequest 应用多个谓词吗?手动解析我的结果会更好吗?
【发布时间】:2011-12-29 02:14:59
【问题描述】:

好的,我有一个基本的 iPad 应用程序,它要求用户提供 5 个搜索/过滤条件。基于这些数据,我需要转到我的核心数据数据库,并提取任何符合该标准的托管对象。似乎我需要对同一个请求应用多个谓词,这可能吗?或者我可以写一个很长的花哨谓词吗?有多重要求?我应该如何处理?

通过获取请求获取所有实体,然后循环遍历每个数组并获取我发现符合搜索条件的任何对象是否是个好主意?

请指教!

【问题讨论】:

    标签: iphone core-data nspredicate nsfetchrequest


    【解决方案1】:

    斯威夫特 4

    let fetchRequest: NSFetchRequest<YourModelEntityName> = YourModelEntityName.fetchRequest()
    
    let fooValue = "foo"
    let barValue = "bar"
    
    let firstAttributePredicate = NSPredicate(format: "firstAttribute = %@", fooValue as CVarArg)
    let secondAttributePredicate = NSPredicate(format: "secondAttribute = %@", barValue as CVarArg)
    
    fetchRequest.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [firstAttributePredicate, secondAttributePredicate])
    

    关于不同类型的NSCompoundPredicate构造函数的更多信息可以找到here

    【讨论】:

      【解决方案2】:

      是的,这是可能的。您正在寻找复合谓词,下面是一个带有 AND 谓词的示例:

      NSPredicate *compoundPredicate 
         = [NSCompoundPredicate andPredicateWithSubpredicates:[NSArray of Predicates]];
      

      您也可以根据需要使用notPredicateWithSubpredicatesorPredicateWithSubpredicates

      链接到文档https://developer.apple.com/documentation/foundation/nscompoundpredicate

      【讨论】:

      • Thanx 伙计,我尝试通过编写一个 NSString 并将其作为格式传递给谓词来做到这一点。这很好用,但不适用于约会!!我浪费了一天的工作。这是创建过滤器的方法:D
      猜你喜欢
      • 2014-08-04
      • 1970-01-01
      • 1970-01-01
      • 2021-04-21
      • 1970-01-01
      • 1970-01-01
      • 2021-12-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多