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
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With