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

你离开我真会死。 提交于 2019-12-24 21:49:31

问题


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.


回答1:


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

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



回答2:


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.




回答3:


Try using NSArray's filteredArrayUsingPredicate: function and write a custom predicate to evaluate the objects in your array.



来源:https://stackoverflow.com/questions/9178585/ios-comparing-2-arrays-and-objects-in-an-array-logic-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!