如何过滤数据是字典数组,每个字典包含NSSet对象

时间:2015-05-20 02:20:09

标签: ios nsmutablearray nsdictionary predicate nsset

我有NSMutableArray NSDictionaries并且每个字典都包含NSSet个对象,它基本上是核心数据中多对多关系的其他实体。 我想要的是基于NSSet的特定值我要过滤我的NSMutableArray。请建议,如何接近。

1 个答案:

答案 0 :(得分:1)

NSPredicate to rescue。

#import <Foundation/Foundation.h>

int main(int argc, char *argv[]) {
    @autoreleasepool {

         // I have NSMutableArray ...
        NSMutableArray *array  = [NSMutableArray new];
        NSArray        *result = nil;

        // ... of NSDictionaries ...
        // ... each dictionary contains NSSet object which is basically other entity ...
        NSDictionary   *dict1  = @{ @"name": @"Adam",
                                     @"age": @(47),
                                     @"children": [NSSet setWithArray:@[ @"Alan", @"Bobby", @"Chuckie" ]]};
        NSDictionary   *dict2  = @{ @"name": @"Bob",
                                     @"age": @(37),
                                     @"children": [NSSet setWithArray:@[ @"Brian", @"Chaz", @"Donald" ]]};
        NSDictionary   *dict3  = @{ @"name": @"Charlie",
                                     @"age": @(27),
                                     @"children": [NSSet setWithArray:@[ @"Caaaaaarl", @"Donnie", @"Eddy" ]]};
        // ... 
        [array addObject:dict1];
        [array addObject:dict2];
        [array addObject:dict3];

        // So, let's find children (stirngs) who contain 'd'
        // This should be Bob and Charlie.

        NSPredicate *predicate = nil;
        predicate = [NSPredicate predicateWithFormat:@"ANY children CONTAINS[cd] %@", @"D"];
        result = [array filteredArrayUsingPredicate:predicate];
        NSLog(@"%@", result);
//          {
//              age = 37;
//              children = "{(\n    Brian,\n    Chaz,\n    Donald\n)}";
//              name = Bob;
//          },
//              {
//              age = 27;
//              children = "{(\n    Donnie,\n    Eddy,\n    Caaaaaarl\n)}";
//              name = Charlie;
//          }
    }
}

如您所见,您可以使用NSPredicate来过滤深层集合。收集操作员会有所不同,具体取决于您要执行的操作。有关更多信息,请访问Apple NSPredicate docs