Search code examples
objective-cdealloc

overriding the dealloc method in objective-c


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.


Solution

  • 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.