为什么%@在predicateWithFormat和stringWithFormat之间表现不同?

Sha*_*yrs 4 predicate objective-c stringwithformat

使用predicateWithFormat,%@被""包围.我们需要使用%K作为密钥.

例如[NSPredicate predicateWithFormat @"%@ == %@" ,@"someKey",@"someValue"]变成

"someKey" == "someValue"
Run Code Online (Sandbox Code Playgroud)

在stringWithFormat时,%@不被""包围

[NSString stringWithFormat @"%@ == %@" ,@"someKey",@"someValue"] 
Run Code Online (Sandbox Code Playgroud)

someKey == someValue

为什么不同?

我错过了什么吗?

为什么在predicateWithFormat中使用%@作为"Value",因为它不是string @WithFormat中%@的含义.为什么不创建一个新的表示法,比如说%V来获得"Value"而%@保持值就像在stringWithFormat中一样.

为什么Apple决定使用相同的符号,即%@应该有不同的含义.

他们真的不一样吧?我错过了什么吗?

All*_*ian 11

字符串变量在谓词中用引号括起,而动态属性(以及键路径)未引用.考虑这个例子:

让我们说我们有一群人:

NSArray *people = @[
    @{ @"name": @"George", @"age": @10 }, 
    @{ @"name": @"Tom", @"age": @15 }
    ];
Run Code Online (Sandbox Code Playgroud)

现在,如果我们想要过滤我们的数组以便按名称查找所有人,我们会期望一个谓词会扩展为如下所示:

name like[c] "George"
Run Code Online (Sandbox Code Playgroud)

这样我们就知道这name是一个动态键,George是一个常量字符串.所以,如果我们使用像@"%@ like[c] %@"扩展谓词这样的格式:

"name" like[c] "George"
Run Code Online (Sandbox Code Playgroud)

这显然不是我们想要的(这里既nameGeorge是常量字符串)

因此构建谓词的正确方法是:

NSPredicate *p = [NSPredicate predicateWithFormat:@"%K like[c] %@", @"name", @"George"];
Run Code Online (Sandbox Code Playgroud)

我希望这是有道理的.您可以在Apple的文档中找到有关谓词的更多信息