Pisan Pisan - 1 year ago 43
Swift Question

Swift: Search for string in core data model

I'm confronted with the following problem in Swift.

I wrote the following function to retrieve all persons in my model with the


private func myFetchRequest()
let moc = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext

let myRequest = NSFetchRequest(entityName: "RegisterOfPersons")

myRequest.predicate = NSPredicate(format: "name = %@", "David")

let results = try moc.executeFetchRequest(myRequest)

for result in results

} catch let error{

Even though my model contains two entries with the
name = "David", the line

myRequest.predicate = NSPredicate(format: "name = %@", "David")

does not find these entries, because "name" is an optional attribute in my model.
Do I have to search for Optional("David"), meaning something like
myRequest.predicate = NSPredicate(format: "name = %@", Optional("David"))

How can I search for all entries with the name "David" in my model? What am I doing wrong?

Thanks for your help!

Answer Source

You are predicating with string so enclose your comparison name with single quote like this

myRequest.predicate = NSPredicate(format: "name = '%@'", "David")  

Also try with Contains

myRequest.predicate = NSPredicate(format: "name CONTAINS[cd] %@", "David")