gpt4 book ai didi

objective-c - 如果子对象在父对象的dealloc中被释放,为什么子对象对父对象的弱引用会为零*

转载 作者:行者123 更新时间:2023-12-03 17:49:02 26 4
gpt4 key购买 nike

*因为子对象是在父对象的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方法内添加/删除观察者。

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


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

现在这是令人困惑的部分。

释放操作的顺序如下:

  • -[MyViewController dealloc]
  • -[MyWindowController 关闭]
  • -[MyViewController removeObserver:MyWindowController]

但是,在 -[MyWindowController close] 点,对 MyViewController 的弱引用为 nil。即使是 MyViewController 首先调用了 close

这会导致问题,因为观察者没有正确删除,然后会引发异常,有时甚至崩溃。

看起来的样子是,在调用-dealloc之前,MyViewController的保留计数已经减少到0,所以MyWindowController 对它的弱引用被设置为 nil。但这对我来说没有意义,因为保留计数似乎会在 -dealloc 之后减少,而且即使情况并非如此,弱引用是nil

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

为什么弱@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.

请注意,它没有说“当对象被释放时”。如果正在调用对象的 dealloc 方法,则根据定义,所有强引用都已被删除。

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

关于objective-c - 如果子对象在父对象的dealloc中被释放,为什么子对象对父对象的弱引用会为零*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33224893/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com