iOS仅将唯一对象添加到NSMutableOrderedSet [英] iOS Only add unique object to NSMutableOrderedSet
问题描述
我有一个NSMutableOrderedSet。我下载了一个 Person对象数组。每个Person对象都有一个唯一的ID。
I have an NSMutableOrderedSet. I download an array of "Person" objects. Each Person object has a unique id.
仅添加NSMutableOrderedSet中尚未添加的Person对象的最有效方法是什么?
What is the most efficient way to only add Person objects that are not already in the NSMutableOrderedSet?
我显然可以遍历整个集合,如果id末尾不存在,则可以添加它-但这似乎是最慢的方法。
I can obviously iterate through the entire set and if the id does not exist at the end then add it - but that seems like the slowest way to do it.
想法?
我在做什么:
for (int x = 0; x < existingSet.Count; x++)
{
if ([personA isEqualto: personB])
break;
if (x == existingSet.Count - 1 && ![person isEqualto: personB])
[existingSet addObject: personA];
}
推荐答案
教您的人班平等是什么意思,因为一个集合只会在发现新对象不等于任何其他对象时才添加新对象。通过覆盖 isEqual:
和 hash
You have to teach your person class what equality means, as a set will only add new object if they are found not to be equal to any other object. do so by overwriting isEqual:
and hash
@interface Person : NSObject
@property (strong) NSNumber *identifier;
@end
@implementation Person
- (BOOL)isEqual:(id)object {
return [self.identifier isEqualToNumber: object.identifier];
}
- (NSUInteger)hash {
return [self.identifier hash]; // if the only field to determine uniqueness is `identifier`, this hashing method is enough
}
@end
比您要做的所有事情
[existingSet addObject: personA];
这将导致与
[existingSet addObject: personA];
[existingSet addObject: personA];
[existingSet addObject: personA];
[existingSet addObject: personA];
,因为只能添加一个相等的对象。另一个 addObject:
调用将自动失败。
as only one equal objects can be added. the other addObject:
calls will fail silently.
一个好阅读: NSHipster:平等
这篇关于iOS仅将唯一对象添加到NSMutableOrderedSet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!