NSPredicate以获取包含特定键值的Array

时间:2016-07-27 10:24:15

标签: ios objective-c nspredicate

使用item - " apple"

获取数组的所有元素

我的输入

item_list: [
    {
        CurrentDate = “4/2/2016";
        search_item =(             
            item_name = @“apple”;
        );
    },
    {
        CurrentDate = “27/1/2016";
        search_item =(
            item_name = @“Ball”;   
        );
    },
    {
        CurrentDate = “17/2/2016";
        search_item =(
            item_name = @“Cat”; 
        );
    },
    {
        CurrentDate = “6/2/2016";
        search_item =(
            item_name = @“apple”;
        );
    },
]

我需要输出

item_list: [
    {
        CurrentDate = “4/2/2016";
        search_item =(             
            item_name = @“apple”;
        );
    },
    {
        CurrentDate = “6/2/2016";
        search_item =(
            item_name = @“apple”;
        );
    },
]

代码我尝试但不工作

NSArray*  filtered = [[item_list valueForKey:@"search_item"] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(item_name == %@)", @“apple”]];

4 个答案:

答案 0 :(得分:2)

看看NSPredicate's predicateWithBlock:而不是predicateWithFormat:我不知道他们如何比较性能,但我发现使用块更容易使用。

以下是一个例子:

[NSPredicate predicateWithBlock:^BOOL(id  _Nonnull evaluatedObject, NSDictionary<NSString *,id> * _Nullable bindings) {
    return [(NSDictionary *)evaluatedObject[@"search_item"][@"item_name"] isEqualToString:@"apple"];
}];

答案 1 :(得分:2)

NSPredicate *predicate =
[NSPredicate predicateWithFormat:@"ANY search_item.item_name CONTAINS[c] %@", @"apple"];  
NSArray *array =[item_list filteredArrayUsingPredicate:predicate];

答案 2 :(得分:1)

您的Predicate是正确的,只需将您的字符串放在single quote

之间即可
NSArray*  filtered = [item_listArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"Any search_item.item_name = '%@'", @“apple”]];

答案 3 :(得分:0)

试试以下......

NSPredicate *predicate =
[NSPredicate predicateWithFormat:@"ANY self.isFree CONTAINS[c] %@", @"YES"]; 
NSArray *array =[item_list filteredArrayUsingPredicate:predicate];