NSPredicate. Unable to create SQL for predicate. I wonder why?

I already solved my problem [Blindly], not understanding the root cause. But I would rather understand the concept of a professional. Could you tell me why below the identical code works and the other does not.

Code 1: not working

//Above code omitted... NSPredicate * predicate = [NSPredicate predicateWithFormat:@"gender == m"]; //NOTICE HERE [request setPredicate:predicate]; NSError *error = nil; self.people = [self.managedObjectContext executeFetchRequest:request error:&error]; //Below code omitted... 

Code 2: Does it work

 //Above code omitted... NSString *type = @"m"; NSPredicate * predicate = [NSPredicate predicateWithFormat:@"gender == %@",type]; //NOTICE HERE [request setPredicate:predicate]; NSError *error = nil; self.people = [self.managedObjectContext executeFetchRequest:request error:&error]; //Below code omitted... 


I forgot to talk about what error I got, I got SIGABRT in the line below, When I executed code 1.
  self.people = [self.managedObjectContext executeFetchRequest:request error:&error]; 

And one more thing: in a GCC error, he could not format the predicate due to "gender == m".


Enlighten me!

thanks

+4
source share
2 answers

See the predicate programming guide (heading "Literals"). You can use literals in your string, but you must enclose them in quotation marks, therefore

 NSPredicate * predicate = [NSPredicate predicateWithFormat:@"gender == 'm'"]; 

It would work. When predicateWithFormat adds to the argument, it knows that it is a string. When you just have m , he does not know what to do with it, therefore, an error.

+10
source

quick example

 let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext! let fetchRequest = NSFetchRequest(entityName:"Words") fetchRequest.predicate = NSPredicate(format: "letter == '\(letter)'") var error: NSError? let fetchedResults = managedContext.executeFetchRequest(fetchRequest, error: &error) as? [NSManagedObject] if let results = fetchedResults { println(results) } else { println("Could not fetch \(error), \(error!.userInfo)") } 
+1
source

All Articles