Reputation: 2842
Can someone tell me what would actually happen if you override the dealloc method in Objective-C? As in would it crash or would it just start leaking memory all over the place. I've been wondering what would happen and why it is necessary to prevent the programmer from using dealloc directly.
And in what case would you had to do something like this?
EDIT: Sorry guys for not being clear. I was mainly talking in terms or ARC type coding.
Upvotes: 2
Views: 6618
Reputation: 9231
Before ARC overriding the dealloc
method was very common, you were releasing the ivars the deallocated instance owned. Now, with ARC, is less common, however, you may have to do it in some special cases, like when you de-register an instance from observing with NSNotificationCenter
.
The rule you talk about was not to call dealloc
directly (not override), that would have usually led to a crash since you were bypassing Cocoa's internal reference counting system.
Edit: Based on your edit, if you call [super dealloc]
under ARC, you'll get a compile time error. And if there was no error, it would have probably lead to duplicating the dealloc
call, which would have made your program crash.
Upvotes: 9
Reputation: 185681
Overriding -dealloc
is an extremely common thing to do in non-ARC code. In fact, you'd be hard-pressed to find a class that doesn't override it.
The key thing to remember, though, is that every single override of -dealloc
always ends with a call to [super dealloc]
.
Of course, in ARC code, overriding -dealloc
is far less common. And if you do override it, you don't call [super dealloc]
, because the compiler will insert that for you. But remember, this is only true under ARC.
Upvotes: 16