如果在父对象的dealloc中释放了子对象,为什么子对象对父对象的弱引用为nil *

If a child object is released in the dealloc of a parent object, why would the child object's weak reference to the parent be nil*

*因为子对象在父对象的 dealloc 中被释放了,这是否意味着父对象仍然存在,并且子对象对父对象的弱引用应该仍然有效吗?

我有一个父对象,一个 NSViewController 子类,它拥有另一个对象,一个 NSWindowController 子类。

@interface MyViewController : NSViewController
@property (strong) MyWindowController *myWindowController;

NSWindowController 子类对 NSViewController

的引用很弱
@interface MyWindowController : NSWindowController
@property (weak) MyViewController *myViewController;

MyViewController 中,我已经覆盖了 -dealloc:

-(void)dealloc
{
   [self.myWindowController close];
   self.myWindowController = nil;
}

MyWindowController 内部,我是 init/close 方法内部的 adding/removing 观察者。

//INIT:
[self.myViewController addObserver:self forKeyPath:NSStringFromSelector(@selector(selectedObjects)) options:kObservingOptions context:nil];


//CLOSE:
[self.myViewController removeObserver:self forKeyPath:NSStringFromSelector(@selector(selectedObjects))];

现在是令人困惑的部分。

解除分配的操作顺序如下:

但是,在 -[MyWindowController close] 点,对 MyViewController 的弱引用是 nil。尽管最初调用 close 的是 MyViewController

这会导致问题,因为观察者没有被正确移除,随后会抛出异常,有时甚至会崩溃。

看起来 的样子,是 MyViewController 的保留计数在调用 -dealloc 之前已经减为 0,所以 MyWindowController 对它的弱引用被设置为 nil。但这对我来说没有意义,因为看起来保留计数会在 after-dealloc 后递减,而且即使不是这种情况,弱者会不会参考是 nil?

这可能只是与 NSViewController 拥有 NSWindowController 的奇怪互动,但这对我来说也没有多大意义

为什么弱@property==nil?

来自苹果的documentation on ARC

A weak reference does not extend the lifetime of the object it points to, and automatically becomes nil when there are no strong references to the object.

请注意,它并没有说 "when an object is deallocated." 如果正在调用一个对象 dealloc 方法,那么根据定义,所有强引用都已被删除。

此外,您不应该在已经解除分配的对象上调用方法。您应该找到一种方法在对象被释放之前注销您的观察者。