5

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!

Nirav D
  • 71,513
  • 12
  • 161
  • 183
Pisan
  • 69
  • 2
  • 10

1 Answers1

12

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") 
Nirav D
  • 71,513
  • 12
  • 161
  • 183
  • This will compare with the literal string %@. From the predicate programming guide "If you use variable substitution using %@ (such as firstName like %@), the quotation marks are added for you automatically." – pbasdf Aug 08 '16 at 15:27
  • @pbasdf I know that but op is using `=` that is the reason suggesting to op to add Single Quote. – Nirav D Aug 08 '16 at 15:29
  • Thank you so much for your answer! I tried as you suggested. However, it still doesn't work. Maybe I am making a mistake somewhere else? – Pisan Aug 08 '16 at 15:31
  • 1
    Is you property name contains David or exact David, if it is contains than you need to use `CONTAINS[C]` instead of `=`. – Nirav D Aug 08 '16 at 15:34
  • Check my edited answer, and give reply is it working or not? – Nirav D Aug 08 '16 at 15:57
  • Thank you very much NDoc! Thanks to your post I found out that the name in the database contained a spelling miss! Thanks for your help guys! – Pisan Aug 08 '16 at 16:26
  • Welcome mate, Happy coding :) – Nirav D Aug 08 '16 at 16:38