具有弱引用的NSHashTable

时间:2014-06-19 15:41:32

标签: ios objective-c cocoa ios7 ios6

我想使用NSHashTable来保持对包含对象的弱引用。关于其他可自定义的行为(包括相等性检查),我想要与NSSet完全相同的行为(所以实际上我想要一个带有弱引用的NSSet)。你能给我一个如何初始化这样一个哈希表的例子吗?

以下是否足够: [NSHashTable hashTableWithOptions:NSPointerFunctionsWeakMemory]

具有弱引用的NSHashTable是否会自动删除已取消分配的对象?

1 个答案:

答案 0 :(得分:9)

是的,您可以使用NSPointerFunctionsWeakMemory。 Facebook KVOController也使用NSHashTable,请参阅KVOController

- (instancetype)init
{
  self = [super init];
  if (nil != self) {
    NSHashTable *infos = [NSHashTable alloc];
#ifdef __IPHONE_OS_VERSION_MIN_REQUIRED
    _infos = [infos initWithOptions:NSPointerFunctionsWeakMemory|NSPointerFunctionsObjectPointerPersonality capacity:0];
#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
    if ([NSHashTable respondsToSelector:@selector(weakObjectsHashTable)]) {
      _infos = [infos initWithOptions:NSPointerFunctionsWeakMemory|NSPointerFunctionsObjectPointerPersonality capacity:0];
    } else {
      // silence deprecated warnings
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
      _infos = [infos initWithOptions:NSPointerFunctionsZeroingWeakMemory|NSPointerFunctionsObjectPointerPersonality capacity:0];
#pragma clang diagnostic pop
    }

#endif
    _lock = OS_SPINLOCK_INIT;
  }
  return self;
}

此外,为了更方便,您可以使用weakObjectsHashTable

  

返回一个新的哈希表,用于存储对其内容的弱引用。

     

返回值使用选项NSHashTableZeroingWeakMemory和NSPointerFunctionsObjectPersonality的新哈希表   初始容量为0。

该文件有点旧,但确实如此。见NSHipster NSHash​Table & NSMap​Table

NSHashTableZeroingWeakMemory: This option has been deprecated. Instead use the NSHashTableWeakMemory option

另请注意

  

NSHashTableWeakMemory等于NSPointerFunctionsWeakMemory

相关问题