iOS仅将唯一对象添加到NSMutableOrderedSet [英] iOS Only add unique object to NSMutableOrderedSet

查看:142
本文介绍了iOS仅将唯一对象添加到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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆