Pisan Pisan - 4 months ago 8
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

name
"David".

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

let myRequest = NSFetchRequest(entityName: "RegisterOfPersons")

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

do{
let results = try moc.executeFetchRequest(myRequest)

for result in results
{
print(result)
}

} catch let error{
print(error)
}
}


Even though my model contains two entries with the
attribute
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

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")