Ask Your Question
2

How can I have several NSPredicates for a NSFetchRequest in Swift?

asked 2021-11-26 11:00:00 +0000

devzero gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2022-08-16 19:00:00 +0000

pufferfish gravatar image

You can create multiple NSPredicates and combine them using NSCompoundPredicate. Here's an example:

let agePredicate = NSPredicate(format: "age > %d", 18)
let namePredicate = NSPredicate(format: "name CONTAINS %@", "John")
let compoundPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [agePredicate, namePredicate])

let fetchRequest: NSFetchRequest<Person> = Person.fetchRequest()
fetchRequest.predicate = compoundPredicate

let results = try? context.fetch(fetchRequest)

In this example, we have two NSPredicates: one for age and one for name. We then combine them using NSCompoundPredicate with the "AND" operator and set it as the fetch request's predicate. Finally, we execute the fetch request and get the results.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-11-26 11:00:00 +0000

Seen: 11 times

Last updated: Aug 16 '22