Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSPredicate - Unable to generate SQL for predicate, I wonder why?

I have already solved my problem [Blindly] without understanding root cause. But I would rather understand a concept from a professional. So could you please tell me why below identical code one works but another doesn't.

Code 1: Doesn't work

//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 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...


Forgot to tell about what error I got, I got SIGABRT on below line, When I executed Code 1.
 self.people = [self.managedObjectContext executeFetchRequest:request error:&error];

And one more thing, in GCC error was it cannot format predicate because of "gender == m".


Enlighten me!!

Thanks

like image 665
TeaCupApp Avatar asked Dec 22 '22 08:12

TeaCupApp


1 Answers

See the predicate programming guide (heading "Literals"). You can use literals in your string but you have to enclose them in quotes, so

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

Would have worked. When predicateWithFormat adds in the argument, it knows it is a string. When you just have m in there, it doesn't know what to do with it, hence the error.

like image 170
jrturton Avatar answered Mar 18 '23 01:03

jrturton