【发布时间】:2013-04-20 16:02:32
【问题描述】:
我在启用 ARC 的 Objective-C 中注意到以下内容:
让我们拥有简单的 A 类和自动合成的弱属性
@interface A
@property (nonatomic, weak) id refObject;
@end
@implementation A
@end
第二类 B 实现了 dealloc
@interface B
@end
@implementation B
-(void) dealloc
{
NSLog(@"In dealloc");
}
@end
最后在 A 类的某个地方有以下内容:
@implementation A
...
-(void) foo
{
B* b = [B new];
self.refObject = b;
// Just use b after the weak assignment
// in order to not dealloc 'b' before assignement
NSLog(@"%@", b);
}
...
@end
如果我在[B dealloc] 中设置断点并检查[A refObject] 属性,我可以看到a.refObject 为nil 但a->_refObject 不是nil 并指向'b'
你知道为什么会这样吗?
【问题讨论】:
-
当访问器方法知道应该清除弱引用时,可能会返回
nil,但实例变量本身保持不变(并被释放,现在它是一个悬空指针)。 -
我认为在 dealloc 中该对象仍然有效并且尚未被删除。例如,您可以从 NSNotificationCenter 注销它并可以访问其属性。
-
“你可以访问它”并不一定意味着它没有被释放,但我可能错了。
标签: objective-c automatic-ref-counting weak-references