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!
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With