gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 03:57:51 25 4
gpt4 key购买 nike

使用 predicateWithFormat,%@ 被 ""包围。我们需要使用 %K 作为键。

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

"someKey" == "someValue"

在 stringWithFormat 中,%@ 没有被 ""包围

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

变成 someKey == someValue

为什么不同?

我错过了什么吗?

为什么在 predicateWithFormat 中使用 %@ 作为“值”,因为它不是 %@ 在 stringWithFormat 中的意思。为什么不创建一个新的表示法,比如 %V 来获取“Value”,而 %@ 像 stringWithFormat 对应物一样保留 Value。

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

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

最佳答案

字符串变量在谓词中用引号括起来,而动态属性(以及因此的键路径)不被引用。考虑这个例子:

假设我们有一群人:

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

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

name like[c] "George"

这样我们就说 name 是一个动态键,而 George 是一个常量字符串。因此,如果我们使用类似 @"%@ like[c] %@" 的格式,扩展谓词将是:

"name" like[c] "George"

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

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

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

我希望这是有道理的。您可以在 Apple 的 documentation here 中找到更多关于谓词的信息。

关于objective-c - 为什么 %@ 在 predicateWithFormat 和 stringWithFormat 之间表现不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14192247/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com