ios 自定义 dealloc 和 ARC (Objective-C)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7292119/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Custom dealloc and ARC (Objective-C)
提问by Niku
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:
.
在我的小 iPad 应用程序中,我有一个使用观察者的“切换语言”功能。每个视图控制器在其viewDidLoad:
.
- (void)viewDidLoad
{
[super viewDidLoad];
[observer registerObject:self];
}
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.
当用户点击“更改语言”按钮时,新语言会存储在我的模型中,观察者会收到通知并updateUi:
在其注册的对象上调用选择器。
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.
这非常有效,除非我在 TabBarController 中有视图控制器。这是因为当标签栏加载时,它从其子控制器获取标签图标而不初始化视图,因此viewDidLoad:
不会被调用,因此这些视图控制器不会收到语言更改通知。因此,我将registerObject:
调用移到了init
方法中。
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
.
回到我过去viewDidLoad:
向观察者注册时,我曾经viewDidUnload:
取消注册。由于我现在正在注册init
,因此取消注册很有意义dealloc
。
But here is my problem. When I write:
但这是我的问题。当我写:
- (void) dealloc
{
[observer unregisterObject:self];
[super dealloc];
}
I get this error:
我收到此错误:
ARC forbids explicit message send of 'dealloc'
ARC 禁止“dealloc”的显式消息发送
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?
由于我需要调用[super dealloc]
以确保超类正确清理,但 ARC 禁止这样做,我现在被卡住了。当我的对象即将死亡时,还有其他方法可以得到通知吗?
回答by justin
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):
使用 ARC 时,您只需不[super dealloc]
显式调用- 编译器会为您处理它(如Clang LLVM ARC 文档第 7.1.2 章所述):
- (void) dealloc
{
[observer unregisterObject:self];
// [super dealloc]; //(provided by the compiler)
}