2013-01-07 47 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執行許多複雜的操作。

相關問題