Use NSCompoundPredicate to retrieve data

When it comes to searching(or retrieve data) in coredata database with multiple conditions, create multiple prediates, use NSCompoundPredicate to combine them,

1
2
3
4
5
let titlePredicate = NSPredicate(format: "title CONTAINS %@", keyword)
let contentPredicate = NSPredicate(format: "content CONTAINS %@", keyword)
let compoundPredicate = NSCompoundPredicate(
type: NSCompoundPredicate.LogicalType.or,
subpredicates: [titlePredicate, contentPredicate])

now use this compound predicate to filter data the way you wanted

1
2
let request: NSFetchRequest<entityName> = entityName.fetchRequest()
request.predicate = compoundPredicate

⚠️ fetch request could be potential errors so make sure use a do-catch statement.

Also the NSPredicate cheatsheet: