Search code examples
objective-ciphonensset

iOS - Comparing 2 Arrays and Objects in an array - Logic Issue


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.


Solution

  • You want to use an NSPredicate with NSArray's filteredArrayUsingPredicate. Something like this:

    NSArray *filteredArray = [personArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"name = \"Jemmy\""]];