简体   繁体   English

Objective-C析构函数与ARC

[英]Objective-C destructor with ARC

I'm trying to create some cleanup code in my Objective-C class, by overwriting dealloc: 我正在尝试通过覆盖dealloc在Objective-C类中创建一些清理代码:

-(void)dealloc {
    //cleanup code
    [super dealloc];
}

Though I cannot do this since [super dealloc] is disallowed by the compiler when ARC is enabled. 虽然我不能这样做,因为启用ARC时编译器不允许[super dealloc] Is there an alternative I can use? 有没有我可以使用的替代方案?

From the Transitioning to ARC Release Notes (emphasis mine): 过渡到ARC发行说明 (强调我的):

You may implement a dealloc method if you need to manage resources other than releasing instance variables. 如果需要管理除释放实例变量之外的资源,则可以实现dealloc方法。 You do not have to (indeed you cannot) release instance variables, but you may need to invoke [systemClassInstance setDelegate:nil] on system classes and other code that isn't compiled using ARC. 您不必(实际上您不能)释放实例变量,但您可能需要在系统类和未使用ARC编译的其他代码上调用[systemClassInstance setDelegate:nil]。

Custom dealloc methods in ARC do not require a call to [super dealloc] (it actually results in a compiler error). ARC中的自定义dealloc方法不需要调用[super dealloc](它实际上会导致编译器错误)。 The chaining to super is automated and enforced by the compiler. 链接到super是由编译器自动执行的。

So you can do the same sort of cleanup in dealloc when using ARC, just don't call super . 所以你在使用ARC时可以在dealloc进行同样的清理,只是不要调用super

When ARC is active you simply don't call [super dealloc] . 当ARC处于活动状态时,您根本不会调用[super dealloc] ARC will do this for you. ARC会为你做这件事。 Alternately, you could have a prepareForDealloc method that allows you to call super and which is called from within dealloc in your base class. 或者,您可以使用prepareForDealloc方法,该方法允许您调用super并从基类中的dealloc中调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM