[英]NSHashTable with weak references
我想使用NSHashTable来保持对包含对象的弱引用。 关于其他可自定义的行为(包括相等性检查),我想要与NSSet完全相同的行为(所以实际上我想要一个带有弱引用的NSSet)。 你能给我一个如何初始化这样一个哈希表的例子吗?
以下就足够了: [NSHashTable hashTableWithOptions:NSPointerFunctionsWeakMemory]
具有弱引用的NSHashTable也会自动删除已取消分配的对象吗?
是的,您可以使用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表和NSMap表
NSHashTableZeroingWeakMemory: This option has been deprecated. Instead use the NSHashTableWeakMemory option
另请注意
NSHashTableWeakMemory等于NSPointerFunctionsWeakMemory
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.