简体   繁体   中英

Objective-C destructor with ARC

I'm trying to create some cleanup code in my Objective-C class, by overwriting dealloc:

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

Though I cannot do this since [super dealloc] is disallowed by the compiler when ARC is enabled. Is there an alternative I can use?

From the Transitioning to ARC Release Notes (emphasis mine):

You may implement a dealloc method if you need to manage resources other than releasing instance variables. 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.

Custom dealloc methods in ARC do not require a call to [super dealloc] (it actually results in a compiler error). The chaining to super is automated and enforced by the compiler.

So you can do the same sort of cleanup in dealloc when using ARC, just don't call super .

When ARC is active you simply don't call [super dealloc] . ARC will do this for you. Alternately, you could have a prepareForDealloc method that allows you to call super and which is called from within dealloc in your base class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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