Ok I have a basic iPad app that asks for 5 search/filter criteria from the user. Based on this data, I need to go to my core data db, and pull out any managed objects that fit that criteria. It seems like I need to apply more than one predicate to the same request, is that possible? Or could I just write a really long fancy predicate? With multiple requirements? How should I approach that?
Would it be a good idea to just grab all the entities through the fetch request, and then loop through each array and grab any objects that I find that fit my search criteria?
Please advise!
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
来源:https://stackoverflow.com/questions/8129508/can-i-apply-multiple-predicates-to-an-nsfetchrequest-would-it-be-better-to-manu