Bangalore
Bangalore

Reputation: 1580

Sorting NSMutableArray based on Key with Predicates not working?

I have a NSMutableArray with more than 150+ objects, and i need to create a new Array based on this key "name" matching with input name.

So i got this predicate code from 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

NOw am getting correct results but along with that am getting extra objects

like for example Consider this is my big list of object

[{
  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
}]

From this i need All name exactly matching to "john"

so the result will be like this

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

But when i use above code iam getting this as final result

 [{
      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
    }]

How can i remove "John Doe" and "John Mark " like i need only a specific text matching "john".

Pls help me

Upvotes: 1

Views: 203

Answers (1)

trojanfoe
trojanfoe

Reputation: 122401

[NSArray filteredArrayUsingPredicate:] returns the filtered array, so:

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

Note: this assumes both arr and selectedDrug are NSDictionary instances.

Upvotes: 2

Related Questions