Why does% @ behave differently between predicateWithFormat and stringWithFormat?

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

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

 "someKey" == "someValue" 

While in stringWithFormat% @ is not surrounded by ""

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

becomes someKey == someValue

Why is the difference?

Did I miss something?

Why use% @ for "Value" in predicateWithFormat, because that is not what% @ means in stringWithFormat. Why not create a new notation, say% V, to get the value "Value" and% @ to remain the value, as in the stringWithFormat mapping.

Why does Apple decide that the same character, namely% @, should mean differently.

Are they really different? Did I miss something?
+4
source share
2 answers

String variables are surrounded by quotation marks in predicates, while dynamic properties (and therefore key paths) are not quoted. Consider this example:

Let's say we have an array of people:

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

Now, if we want to filter our array to find all the people by name, we expect the predicate to expand like this:

 name like[c] "George" 

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

 "name" like[c] "George" 

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

Thus, the correct way to construct our predicate is as follows:

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

I hope this makes sense. You can find much more in the predicates in the Apple documentation here.

+11
source

Well, NSPredicate is a function to evaluate some string. Look at this example and NSString stringWithFormat only copies the value pointed to the appropriate place -% @. The usage is completely different and you can do a lot of complex work with NSPredicate.

+1
source

All Articles