comparing object attribute in one array to an object attribute in another array

六眼飞鱼酱① 提交于 2019-12-25 07:27:18

问题


i seem to be having difficulties in accessing and comparing objects in NSMutableArrays in objective c. I'm very new so when explaining , some code would be nice. I have a character class and a characterfound class. The code looks like this:

@implementation character

@synthesize IDE, name;

- (void) dealloc {
    [text release];
    [super dealloc];
}

@implementation characterfound

@synthesize IDE;

- (void) dealloc {
    [text release];
    [super dealloc];
}

I have two arrays which are being filled with names and id's. If I want to compare just the id's to build a new array or do something else with it. How do I do this.

for instance

**character[]**
name :joe smith
IDE: ik321

name :james smith
IDE: ik32a

**characterfound[]**

IDE:2343k
IDE:ik32a 

so when I compare the two ,the id will be found and I can put the name in another array. Or output it..

I'll try to refrase my question and be more specific thnx for replying btw. I have two classes the character class @interface character : NSObject { // attributes NSInteger type; NSInteger rep1, rep2, rep3, rep4, rep5; NSString *name; NSString *IDE;

} and the characterfound class

@interface characterfound : NSObject { // attributes //NSInteger IDE; NSInteger type; NSString *IDE;

}

When I'm parsing an xml file it encounters different tags and such and fills my characterclass accordingly

for instance

also there is some other xml in the foundcharacter like so:

so my first array will be filled with the character object including it's attributes and the second array foundcharacter will be as well. characterarray = [character1 name="johnson" id="jfja33", character2 name="smith" id="sdfae23"]

characterfoundarray [characterfound ide ="jfja33 , characterfound2 ide="jap234" ]; So my arrays are being filled with objects and their attributes and I would like to compare the attributes( if that's possible ) and create an output.


回答1:


If looking up character objects by ID is a common operation, you should create a mapping from id's to character objects, at which point doing the lookup from your second array will be trivial:

NSMutableDictionary* charactersById = [NSMutableDictionary dictionary];
for (Character* character in characters) {
    [charactersById setObject:character forKey:[character IDE]];
}

(Note that I've made your class upper-case for the example code; you should do the same in your code since writing code that ignores standard language conventions is a bad idea in any language; it significantly reduces the readability of your code.)



来源:https://stackoverflow.com/questions/1150177/comparing-object-attribute-in-one-array-to-an-object-attribute-in-another-array

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