Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Who calls the dealloc method and when in Objective C?

When a custom class is created in Objective C, when and how is the dealloc method called? Is it something that I have to implement somehow in my class?

like image 737
Sujal Avatar asked Aug 17 '11 12:08

Sujal


People also ask

What does dealloc do?

Deallocates the memory occupied by the receiver.

What is Dealloc in C++?

-dealloc is an Objective-C selector that is sent by the Objective-C runtime to an object when the object is no longer owned by any part of the application. -release is the selector you send to an object to indicate that you are relinquishing ownership of that object.


1 Answers

You never send a dealloc message directly. Instead, an object’s dealloc method is invoked indirectly through the release NSObject protocol method (if the release message results in the receiver's retain count becoming 0). See Memory Management Programming Guide for more details on the use of these methods.

Subclasses must implement their own versions of dealloc to allow the release of any additional memory consumed by the object—such as dynamically allocated storage for data or object instance variables owned by the deallocated object. After performing the class-specific deallocation, the subclass method should incorporate superclass versions of dealloc through a message to super:

Important: Note that when an application terminates, objects may not be sent a dealloc message since the process’s memory is automatically cleared on exit—it is more efficient simply to allow the operating system to clean up resources than to invoke all the memory management methods. For this and other reasons, you should not manage scarce resources in dealloc

 - (void)release
 {
   _retainCount--;
   if (_retainCount == 0) {
       [self dealloc];
    }
  }
like image 151
PJR Avatar answered Sep 20 '22 06:09

PJR