Tah*_*mad 10 cocoa objective-c ios ios6 ios7
我想使用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;
}
Run Code Online (Sandbox Code Playgroud)
另外,为了更方便,您可以使用 weakObjectsHashTable
返回一个新的哈希表,用于存储对其内容的弱引用.
返回值一个新的哈希表,它使用选项NSHashTableZeroingWeakMemory和NSPointerFunctionsObjectPersonality,初始容量为0.
该文件有点旧,但确实如此.参见NSHipster NSHash表和NSMap表
NSHashTableZeroingWeakMemory: This option has been deprecated. Instead use the NSHashTableWeakMemory option
Run Code Online (Sandbox Code Playgroud)
另请注意
NSHashTableWeakMemory等于NSPointerFunctionsWeakMemory
| 归档时间: |
|
| 查看次数: |
4060 次 |
| 最近记录: |