自定义 dealloc 和 ARC (Objective-C) [英] Custom dealloc and ARC (Objective-C)

查看:22
本文介绍了自定义 dealloc 和 ARC (Objective-C)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的小 iPad 应用程序中,我有一个使用观察者的切换语言"功能.每个视图控制器在其 viewDidLoad: 期间向我的观察者注册自己.

In my little iPad app I have a "switch language" function that uses an observer. Every view controller registers itself with my observer during its viewDidLoad:.

- (void)viewDidLoad
{
    [super viewDidLoad];
    [observer registerObject:self];
}

当用户点击更改语言"按钮时,新语言会存储在我的模型中,观察者会收到通知并在其注册的对象上调用 updateUi: 选择器.

When the user hits the "change language" button, the new language is stored in my model and the observer is notified and calls an updateUi: selector on its registered objects.

这很有效,除非我在 TabBarController 中有视图控制器.这是因为当标签栏加载时,它从它的子控制器获取标签图标而不初始化视图,所以 viewDidLoad: 没有被调用,所以那些视图控制器不会收到语言更改通知.因此,我将 registerObject: 调用移到了 init 方法中.

This works very well, except for when I have view controllers in a TabBarController. This is because when the tab bar loads, it fetches the tab icons from its child controllers without initializing the views, so viewDidLoad: isn't called, so those view controllers don't receive language change notifications. Because of this, I moved my registerObject: calls into the init method.

当我使用 viewDidLoad: 向我的观察者注册时,我使用 viewDidUnload: 取消注册.由于我现在在 init 中注册,因此在 dealloc 中取消注册很有意义.

Back when I used viewDidLoad: to register with my observer, I used viewDidUnload: to unregister. Since I'm now registering in init, it makes a lot of sense to unregister in dealloc.

但这是我的问题.当我写:

But here is my problem. When I write:

- (void) dealloc
{
    [observer unregisterObject:self];
    [super dealloc];
}

我收到此错误:

ARC 禁止'dealloc'的显式消息发送

ARC forbids explicit message send of 'dealloc'

由于我需要调用 [super dealloc] 来确保超类正确清理,但 ARC 禁止这样做,我现在被卡住了.当我的对象即将死亡时,还有其他方法可以得到通知吗?

Since I need to call [super dealloc] to ensure superclasses clean up properly, but ARC forbids that, I'm now stuck. Is there another way to get informed when my object is dying?

推荐答案

使用 ARC 时,您只需不显式调用 [super dealloc] - 编译器会为您处理它(如Clang LLVM ARC 文档,第 7.1.2 章):

When using ARC, you simply do not call [super dealloc] explicitly - the compiler handles it for you (as described in the Clang LLVM ARC document, chapter 7.1.2):

- (void) dealloc
{
    [observer unregisterObject:self];
    // [super dealloc]; //(provided by the compiler)
}

这篇关于自定义 dealloc 和 ARC (Objective-C)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆