Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
652 views
in Technique[技术] by (71.8m points)

iphone - Objective c - NSMutableSet unique object property

In my app I have a class Person with personId property.
Now I need some data structure to hold a bunch of unique Person objects (unique = different personId)

So I guess I should use NSMutableSet as my data structure, but how do I make the NSMutableSet compare the personId property when adding a person (so I won't add the same person more then ones)?

My goal is to have a collection of unique persons all the time (even if I add two persons with the same id), I want that the NSMutableSet will do all the hard work for me and if I'm adding a person that already exists it won't add it twice.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can achieve that by understanding how the comparison is made by the NSSet. When you add a new object to the set, isEqual: method is called (it's an NSObject method) against each of the set's elements. So what you can do is override this method and provide a custom comparison like this:

NOTE:

If you override isEqual: method you must override hash method as well

// In your Person.m
- (BOOL)isEqual:(id)anObject
{
    return [self.personId isEqual:anObject.personId]; 
    // If it's an object. Otherwise use a simple comparison like self.personId == anObject.personId
}

- (NSUInteger)hash
{
    return self.personId; //Must be a unique unsigned integer
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...