Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 341
Pisan Avatar asked Dec 19 '22 14:12

Pisan


1 Answers

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") 
like image 161
Nirav D Avatar answered Jan 05 '23 22:01

Nirav D