joe*_*usp 5 objective-c ios automatic-ref-counting
那么,apple的[NSHashTable weakObjectsHashTable]状态文档:
返回一个新的哈希表,用于存储对其内容的弱引用.
所以,当我运行以下代码时......
NSHashTable *hashTable = [NSHashTable weakObjectsHashTable];
ABC *object = [[ABC alloc] init];
[hashTable addObject:object];
NSLog(@"%@", [hashTable anyObject]);
object = nil;
NSLog(@"%@", [hashTable anyObject]);
Run Code Online (Sandbox Code Playgroud)
输出是:
2017-09-18 12:57:02.801 Test2[6912:640614] <ABC: 0x608000014eb0>
2017-09-18 12:57:02.801 Test2[6912:640614] <ABC: 0x608000014eb0>
2017-09-18 12:57:02.803 Test2[6912:640614] dealloc // (dealloc of ABC)
Run Code Online (Sandbox Code Playgroud)
看起来调用NSLog(@"%@", [hashTable anyObject]);是保留对象.
如果我打电话,
NSHashTable *hashTable = [NSHashTable weakObjectsHashTable];
ABC *object = [[ABC alloc] init];
[hashTable addObject:object];
//NSLog(@"%@", [hashTable anyObject]);
object = nil;
NSLog(@"%@", [hashTable anyObject]);
Run Code Online (Sandbox Code Playgroud)
产量如预期:
2017-09-18 13:00:23.949 Test2[6936:645459] dealloc
2017-09-18 13:00:23.949 Test2[6936:645459] (null)
Run Code Online (Sandbox Code Playgroud)
谁能告诉我我的误解在哪里?
您甚至不必调用NSLog - 只需执行[hashTable anyObject]即可使对象保持不变.原因似乎是anyObject返回一个自动释放的引用,它不会被释放:d直到将来的某个点.将整个事物包装在@autorelease块中,我相信它会按预期工作.
一般来说,确定ARC:ed对象何时会被释放是很危险的,因为有很多这样的魔法.