Question

With predicateWithFormat, %@ becomes surrounded by "". We need to use %K for keys.

For example [NSPredicate predicateWithFormat @"%@ == %@" ,@"someKey",@"someValue"] becomes

"someKey" == "someValue"

While at stringWithFormat, %@ is not surrounded by ""

[NSString stringWithFormat @"%@ == %@" ,@"someKey",@"someValue"] 

becomes someKey == someValue

Why the difference?

Am I missing something?

Why use %@ for "Value" in predicateWithFormat because it's not what %@ mean in stringWithFormat. Why not create a new notation, say %V to get "Value" and %@ remain Value like in the stringWithFormat counterpart.

Why Apple decides that the same symbol, namely %@ should mean differently.

They really are different right? Am I missing anything?

Was it helpful?

Solution

String variables are surrounded with quotation marks in predicates while dynamic properties (and hence keypaths) are not quoted. Consider this example:

Lets say we have an array of people:

NSArray *people = @[
    @{ @"name": @"George", @"age": @10 }, 
    @{ @"name": @"Tom", @"age": @15 }
    ];

Now if we wanted to filter our array in order to find all persons by name, we would expect a predicate that would expand to something like this:

name like[c] "George"

That way we say that name is a dynamic key and George is a constant string. So, if we used a format like @"%@ like[c] %@" the expanded predicate would be:

"name" like[c] "George"

which is clearly not what we want (here both name and George are constant strings)

So the correct way to build our predicate would be:

NSPredicate *p = [NSPredicate predicateWithFormat:@"%K like[c] %@", @"name", @"George"];

I hope that this makes sense. You can find much more on predicates in Apple's documentation here

OTHER TIPS

Well, NSPredicate is a function to evaluate some string, Look at this example and NSString stringWithFormat only copy the value that is given to the corresponding place -- %@. The usage is totally different, and you can do a lot of complex operation with NSPredicate.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top