NSPredicate用于字典数组,而dict具有数组值

时间:2014-08-14 04:13:26

标签: ios nspredicate

我有一个带字典的数组。字典的值为数组,如:

{ @"categories" : [@"equipment", @"weapon", @"sword"] }

我想找出那个数组中包含武器的所有字典,我试过:

NSString *category = @"weapon";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.categories contains %@", category];
NSArray *resultArray = [dictionaryArray filteredArrayUsingPredicate:predicate]; 

但是resultArray是空的。 我该怎么办呢?

1 个答案:

答案 0 :(得分:0)

你可以试试这个,

NSString *category = @"weapon";
NSArray *items = @[@{ @"categories" : @[@"equipment", @"weapon", @"sword"] },
                    @{ @"categories" : @[@"toys", @"weapon", @"sword"] },
                    @{ @"categories" : @[@"arrow", @"bow", @"sword"] }];
NSPredicate*predicate = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
    NSArray *categories = [evaluatedObject objectForKey:@"categories"];
    return [categories containsObject:category];
}];
NSArray *filteredArray = [items filteredArrayUsingPredicate:predicate];

在我的情况下,它输出如,

(
{
    categories =     (
        equipment,
        weapon,
        sword
    );
},
{
    categories =     (
        toys,
        weapon,
        sword
    );
}