根据字典键过滤NSMutableArray

时间:2014-10-08 11:30:50

标签: ios objective-c dictionary

我有多个dictionarys的数组。其中包含不同的键。这里我有goalType每个目标包含我想根据goalType过滤记录的记录数。请检查以下格式。

 Array==>(  {
         goalType = 1;
         languagetype = 1;
         soundid = 19;
         status = 1;
     },
         {
         goalType = 1;
         languagetype = 1;
         soundid = 20;
         status = 1;
     },
         {
         goalType = 2;
         languagetype = 1;
         soundid = 21;
         status = 1;
     },
         {
         goalType = 2;
         languagetype = 1;
         soundid = 22;
         status = 1;
     },
         {
         goalType = 2;
         languagetype = 1;
         soundid = 23;
         status = 1;
     },
 )

我写了下面的代码,但过滤后的数组变空了

 NSPredicate *predicate = [NSPredicate predicateWithFormat:@"goalType == %@ && languagetype == %d && status == 1 && soundid <= 3884", 
                          [NSNumber numberWithInt:goalType.integerValue],languageid];
 [dataSource predicate];

2 个答案:

答案 0 :(得分:0)

NSDictionary *theDict = @{@"goalType":@(1),@"languagetype":@(1),@"soundid":@(19),@"status":@(1)};
NSDictionary *theDict1 = @{@"goalType":@(1),@"languagetype":@(1),@"soundid":@(20),@"status":@(1)};
NSDictionary *theDict2 = @{@"goalType":@(2),@"languagetype":@(1),@"soundid":@(21),@"status":@(1)};
NSDictionary *theDict3 = @{@"goalType":@(2),@"languagetype":@(1),@"soundid":@(23),@"status":@(1)};


NSMutableArray *testArray = [NSMutableArray array];
[testArray addObject:theDict];
[testArray addObject:theDict1];
[testArray addObject:theDict2];
[testArray addObject:theDict3];

NSPredicate *predicate =   [NSPredicate predicateWithFormat:@"goalType == %@ && languagetype == %@ && status = 1 && soundid <= 3884", [NSNumber numberWithInt:1],[NSNumber numberWithInt:1]];

NSArray *filteredArray = [testArray filteredArrayUsingPredicate:predicate];
NSLog(@"%@",filteredArray);

这是代码有效。

答案 1 :(得分:0)

为什么不使用

NSArray's filteredArrayUsingPredicate:
Evaluates a given predicate against each object in the receiving array and returns a new array containing the objects for which the predicate returns true.

我不知道

[NSArray predicate]

选择器。我很惊讶你没有得到NoM​​ethodFound异常。