2013-01-07 48 views
4

使用predicateWithFormat,%@被“”包围。我们需要为键使用%K。为什么%@在predicateWithFormat和stringWithFormat之间有不同的表现?

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

"someKey" == "someValue" 

虽然在stringWithFormat,%@不被包围 “”

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

成为someKey == someValue

为什么不同?

我错过了什么吗?

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

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

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

回答

11

在谓词中用引号包围字符串变量,而动态属性(因此不引用keypath)。考虑下面这个例子:

假设我们有人民的数组:

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

+0

在我问这个问题之前,我完全理解了这一点。但是为什么在谓词中使用%@作为“Value”。为什么不创建一个新的表示法,例如%V来获取“Value”和%@仍然像stringWithFormat对应值那样。 –

+0

嗯,这不完全正确'%@'只会在字符串对象上添加引号,例如,如果您将它与'NSNumber'(例如'age ==%@')一起使用,它将**不引用该值(它会扩展到'age == 10')。 – Alladinian

+0

我知道,但即使对于字符串对象,%@也不会为stringWithFormat添加引号。所以基本上,%@对于字符串对象的predicateWithFormat行为异常。不寻常是不好的。 –

1

那么,NSPredicate是一个函数来评估一些字符串,Look at this example 和NSString stringWithFormat只复制给出的值给相应的地方 - %@。 使用情况完全不同,您可以使用NSPredicate执行许多复杂的操作。

相关问题