Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 551
yuikonnu Avatar asked May 03 '13 11:05

yuikonnu


2 Answers

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.

like image 95
omz Avatar answered Sep 27 '22 15:09

omz


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.

like image 36
aLevelOfIndirection Avatar answered Sep 27 '22 15:09

aLevelOfIndirection