Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSPredicate Single Quote Issue

Now i'm facing single quote ( ' ) problems in NSPredicate.

here is my query:

 NSPredicate *query = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"s_name='%@' AND s_regno=%d",Name,[RegNo intValue]]];

when i filter with the name, "John", it is ok and no error at all. But i use the name, "Mary ' Monny". there is an error.

i suspect it is because of single quote. pls help me how to overcome this issue.

Thanks

like image 990
Dartfrog Imi Avatar asked Jan 02 '13 02:01

Dartfrog Imi


2 Answers

As a quick fix, you shouldn't need the NSString part at all. This substitution is the whole point of the predicateWithFormat: method! Simply use:

NSPredicate *query = [NSPredicate predicateWithFormat:@"s_name == %@ AND s_regno == %d", Name, [RegNo intValue]];

I like to avoid the format strings entirely, and instead build the predicate in code.

NSPredicate *nameQuery =
[NSComparisonPredicate predicateWithLeftExpression:[NSExpression expressionForKeyPath:@"s_name"]
                                   rightExpression:[NSExpression expressionForConstantValue:Name]
                                          modifier:NSDirectPredicateModifier
                                              type:NSLikePredicateOperatorType
                                           options:NSCaseInsensitivePredicateOption|NSDiacriticInsensitivePredicateOption];

NSPredicate *regNoQuery =
[NSComparisonPredicate predicateWithLeftExpression:[NSExpression expressionForKeyPath:@"s_regno"]
                                   rightExpression:[NSExpression expressionForConstantValue:RegNo]
                                          modifier:NSDirectPredicateModifier
                                              type:NSEqualToPredicateOperatorType
                                           options:0];

NSPredicate *query = [NSCompoundPredicate andPredicateWithSubpredicates:@[nameQuery,regNoQuery]];

Note that I added NSCaseInsensitivePredicateOption|NSDiacriticInsensitivePredicateOption to do a case- and diacritic-insensitive comparison on the name, as in s_name like[cd] %@. If you don't need that, you can of course use type:NSEqualToPredicateOperatorType and options:0.

like image 52
Sterling Archer Avatar answered Nov 01 '22 15:11

Sterling Archer


If name = @"Bell's", you can try to make predicate like this:

NSPredicate *query = [NSPredicate predicateWithFormat:@"name == \"%@\"", name];  

Just replace standard single quotes with double quotes.

like image 32
landonandrey Avatar answered Nov 01 '22 14:11

landonandrey