2013-04-05 58 views
9

我有NSArrayNSDictionaries。其中一個數組中的一個字典鍵包含一個值。我想用該值檢索NSDictionary從NSArray中檢索NSDictionary,其中字典鍵具有值X

我的數組:

Array: (
     { 
     DisplayName = "level"; 
     InternalName = "Number 2"; 
     NumberValue = 1; 
    }, 
     { 
     DisplayName = "PurchaseAmount"; 
     InternalName = "Number 1"; 
     NumberValue = 3500; 
    } 
) 

所以,我想獲得它包含DisplayName設置爲PurchaseAmount(不區分大小寫)的字典。

我該如何做到這一點?

+3

您應該能夠使用'NSPredicate'了點。 [在這裏看到類似的例子](http://stackoverflow.com/q/958622/119114)。 – Nate 2013-04-05 10:13:59

+0

Thnx的小費。我會將我用過的解決方案添加到答案 – 2013-04-05 10:17:01

回答

17

下面的解決我的問題:

NSArray *filtered = [promotions filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(DisplayName == %@)", @"PurchaseAmount"]]; 
NSDictionary *item = [filtered objectAtIndex:0]; 

日Thnx到用戶Nate對我的問題發表評論!

+3

其實,這個答案和[特別是lindinax的回答](http://stackoverflow.com/a/15831638/119114)都比你接受的更好。 Bhargavi的答案檢查一個鍵*包含*字符串,但是您的問題要求鍵與某個值相等的結果。一般來說,這兩個不是一回事。這對您的關鍵名稱可能沒有什麼不同,但對於其他人來說,它可以做得很好。 – Nate 2013-04-05 21:01:38

+0

當您要求輸入「不區分大小寫」時,您正在回答自己的問題。特別是當你把它設定爲接受的。 – lindinax 2014-01-17 16:24:25

5

使用NSPredicate這樣

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"DisplayName LIKE[cd] 'PurchaseAmount' "]; 
NSArray *filter = [array filteredArrayUsingPredicate:predicate]; 
NSLog(@"%@",filter); 

這裏過濾器會牽着你的字典包含顯示名稱設置爲PurchaseAmount(不區分大小寫)

+0

好!謝謝。最好是我最近找到的解決方案。 – 2013-04-05 10:20:10

+0

實際上,這不是**問題。您的謂詞查找匹配**包含**字符串的位置。如果還有另一個密鑰是此密鑰名稱的超集,則您的過濾器會給出* false positive *。 (例如'DisplayName =「PurchaseAmountWithTax」';) – Nate 2013-04-05 20:58:07

+0

即使Bhargavi的解決方案確實有用,你是對的! – 2013-04-09 10:44:38

9

LIKE [CD]也會做

NSArray *filtered = [data filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(DisplayName LIKE[cd] %@)", @"purchaseAmount"]]; 

返回

<NSArray>(
    { 
     DisplayName = PurchaseAmount; 
     InternaName = "Number 1"; 
     NumberValue = 3500; 
    } 
) 
0
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"DisplayName == 'level'"]; 
    NSArray *arrOutput = [[Array filteredArrayUsingPredicate:predicate] mutableCopy]; 

的幫助的2行以上,你會得到所有的字典,顯示名稱= 「PurchaseAmount」

3

回答Swift,

let predicate = NSPredicate(format: "name contains[cd] %@", stringLookingFor) 
let newList = data .filteredArrayUsingPredicate(predicate) 

數據的NSArray像這樣

[ 
{ 
    name = Carlos, 
    total = 9 
}, 
{ 
    name = Willy, 
    total = 2 
} 
]