Can I apply multiple predicates to an NSFetchRequest? Would it be better to manually parse my results?

邮差的信 提交于 2019-12-02 17:29:34
Rog

Yes it's possible. You're looking for compound predicates and here's an example with AND predicates:

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

You can also use notPredicateWithSubpredicates and orPredicateWithSubpredicates depending on your needs.

Link to documentation https://developer.apple.com/documentation/foundation/nscompoundpredicate

Swift 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])

more information about different types of NSCompoundPredicate constructors can be found here

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!