【问题标题】:Where do we put code that was in -dealloc when converting to ARC?转换为 ARC 时,我们将 -dealloc 中的代码放在哪里?
【发布时间】:2012-05-05 12:58:47
【问题描述】:

我有一个类在 dealloc 中调用这个方法:

- (void)dealloc {

    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];
}

将课程转换为 ARC 后,我会在哪里将自己从通知中心移除?它应该在 viewDidUnload 中吗?该通知用于侦听来自模态视图控制器的事件,因此我无法将此代码放入 viewWillDisappear。

【问题讨论】:

    标签: iphone objective-c ios automatic-ref-counting


    【解决方案1】:

    dealloc 保留在 ARC 中,只是您不应该再调用 [super dealloc]:编译器会为您插入代码。当然,所有对release 的调用都不能在dealloc(或其他任何地方)进行。

    - (void)dealloc {
        [[NSNotificationCenter defaultCenter] removeObserver:self];
        // [super dealloc]; <<== Compiler inserts this for you
    }
    

    【讨论】: