2017-03-02 48 views
3

的陣列計數我有格式的陣列如下面濾波的方法與NSPredicate,用於內部字典陣列內部陣列

[ 
    { 
     "xyz" : [Array with different values]; 
     ... many more keys    
    }, 
    { 
    .. same as above dictionary 
    } 
    ... many more dictionaries 
] 

這裏看到,我有字典,其中每個字典具有不同的密鑰的主陣列,其中有是「xyz」鍵,其值又是一個數組。現在我想要那些xyz的數組必須count> 2的字典。

現在,我已經嘗試用以下斷言:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"xyz.count>2"]; 
NSArray *filteredArray = [resultArray filteredArrayUsingPredicate:predicate]; 

但是這是給我錯誤這樣的事情,xyz is not key-value complaint for key "count"

回答

3

在這種情況下導致-valueForKey: @"count"被髮送到每個XYZ實例,XYZ不是計數的關鍵值編碼。

相反,使用@count運營商能夠評估收集的數量,當你想計數,然後使用

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"[email protected]>2"]; 

,而不是

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"xyz.count>2"]; 
1

在雨燕3.0:

let fileterdArray = resultArray.filtered(using: NSPredicate.init(format: "[email protected]>%d", 2))