objective-c - Apple 是如何实现 NSSet 的?

标签 objective-c nsset

Apple 的文档目前没有记录 NSSet 的“身份”概念。

我有一些错误似乎来自 Apple 的代码。例如,“[NSMutableSet minusSet]”从来没有像记录的那样对我有用——但我很确定这是因为“身份”。

例如来自:http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSSet_Class/Reference/Reference.html#//apple_ref/occ/cl/NSSet

containsObject:

Returns a Boolean value that indicates whether a given object is present in the set.

YES if anObject is present in the set, otherwise NO.

这是什么意思?

仅供引用我尝试过的事情:

  1. 在集合中的所有类上实现了“isEqual:”
  2. 检查所有类都是同一个类(没有子类/父类(super class)混淆)
  3. 对集合中的所有类实现 NSCopying(无效)

最佳答案

在 Cocoa 中,对象相等是通过使用 isEqual: hash:

https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html

来自 isEqual: 的注释:

If two objects are equal, they must have the same hash value. This last point is particularly important if you define isEqual: in a subclass and intend to put instances of that subclass into a collection. Make sure you also define hash in your subclass.

您的子类将需要实现这两个,以便它们返回相同的东西。一旦他们这样做,他们就可以在 Cocoa Collections 中正确使用。

NSSet 相等性不起作用的原因是因为集合使用哈希(它存储为哈希表),因此如果您只实现了 isEqual:,那么他们的哈希值有可能(很有可能)不同。

关于objective-c - Apple 是如何实现 NSSet 的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13271160/

相关文章:

swift - 从一对多关系中搜索/检索单个值 Core Data Swift

cocoa - 在 Swift 中创建唯一成员集合

objective-c - 渲染/快照 SpriteKit 场景到 NSImage

cocoa - 将 NSSet 作为 Core Data 中 NSManagedObject 的一部分

ios - 在子类中实现 textRectForBounds 和 editingRectForBounds 后,UITextField 没有滚动到末尾?

objective-c - 翻转、增长和翻译动画

objective-c - 将项目从 NSArray 传输到 NSSet for NSManagedObject

ios - 减去数组,关于字典中的键

ios - 检测 iOS 应用程序中的日期变化

objective-c - NSTask + ps + App Sandbox = 错误