基于Key的谓词不能正常排序NSMutableArray?

时间:2016-02-12 14:12:28

标签: ios objective-c nsmutablearray nspredicate

我有一个超过150个对象的NSMutableArray,我需要根据与输入名称匹配的键“name”创建一个新的数组。

所以我从stackoverflow获得了这个谓词代码

    NSMutableArray *listForm=[[NSMutableArray alloc]init]; //copy Original Array
    listForm=[arr valueForKey:@"data"]; //copied
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name == [c] %@", [selectedDrug valueForKey:@"name"]]; //checking name 

    NSLog(@"%@",[selectedDrug valueForKey:@"name"]); //my input name for matching

    [listForm filteredArrayUsingPredicate:predicate];  


    NSLog(@"%@",listForm);//final result

没有得到正确的结果,但随之而来的是获得额外的物品

例如  考虑这是我的对象

的大清单
[{
  name:"john",
  location:"washington",
  age:23
},{
  name:"Zirad kan",
  location:"iceland",
  age:23
},{
  name:"john",
  location:"usa",
  age:43
},{
  name:"riya",
  location:"india",
  age:20
},{
  name:"Rachel",
  location:"netherland",
  age:33
},{
  name:"john Mark",
  location:"washington",
  age:23
},{
  name:"john Doe",
  location:"washington",
  age:23
}]

从此我需要所有名字与“john”完全匹配

所以结果就像这样

 [{
      name:"john",
      location:"washington",
      age:23
    },{
      name:"john",
      location:"usa",
      age:43
    }]

但是当我使用上面的代码时,我将其作为最终结果

 [{
      name:"john",
      location:"washington",
      age:23
    },{
      name:"john",
      location:"usa",
      age:43
    },{
      name:"john Mark",
      location:"washington",
      age:23
    },{
      name:"john Doe",
      location:"washington",
      age:23
    }]

我如何删除“John Doe”和“John Mark”,就像我只需要一个匹配“john”的特定文字一样。

请帮助我

1 个答案:

答案 0 :(得分:2)

[NSArray filteredArrayUsingPredicate:]返回已过滤的数组,所以:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name == [c] %@",
    selectedDrug[@"name"]]; 
NSArray *filtered = [arr[@"data"] filteredArrayUsingPredicate:predicate];  

注意:这假定arrselectedDrug都是NSDictionary个实例。