Reputation: 2121
I have an NSArray
which contains Person
objects.
This person object contains the following;
> Name
> Age
> School
> Address
> Telephone_Number
Later on i will be setting values to this person object, like person.Name=@"Jemmy";
(but i will not be setting other attributes, Age, School etc.).
I have an NSArray
called personArray
, and it contains 1000 person object records in it. Now i need to Filter out all the objects that contains the Name
Jemmy
. How can i do this ?
What i was thinking of doing is;
NSMutableArray *arrayThatContainAllPersonObjects = [NSMutableArray arrayWithArray:personArray];
[arrayThatContainAllPersonObjects removeObjectsInArray:arrayWeAddedTheName];
But, what i will get is, an array that doesn't have my filter results. Anyway this might not be the correct approach. I believe we could use NSSets
, UNIONS
to solve this.
note:Some might say that this is a duplicate question, but i have searched so much on this.
Upvotes: 0
Views: 471
Reputation: 16725
You want to use an NSPredicate with NSArray's filteredArrayUsingPredicate
. Something like this:
NSArray *filteredArray = [personArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"name = \"Jemmy\""]];
Upvotes: 4
Reputation: 7706
If the Jemmy's are all identical the easy option is
NSArray * cleanArray = [arrayWithAll removeObjectIdenticalTo:jemmyPerson];
If that is not the case (they are called Jemmy - but have different schools or whatever) you are down to
NSArray * cleanArray = [arrayWithAll filterUsingPredicate:jemmyPredicate];
or similar with a block/iteration. The predicate can be constructed with something like:
NSPredicate jemmyPredicate = [NSPredicate predicateWithFormat:@"name == \"jemmy\"];
or
NSPredicate jemmyPredicate = [NSPredicate predicateWithBlock:^(id evaluatedObject, NSDictionary *bindings){
return [evaluatedObject.Name isEqual:@"Jemmy"];
}];
consult the predicate page for more details.
Upvotes: 3