Deallocating Objects
When an
object
is ready to be destroyed (as determined by the reference counting
mechanism), the system will give the object an opportunity to clean
up after itself by calling the
dealloc
method defined by
NSObject. If the object has created or retained
any other objects’ reference by its instance
variables, it must implement this method and perform the appropriate
tasks to maintain integrity of the reference counting system.
In Example 1-8, the Song class
retains the title instance variable in the
setTitle: method. To properly implement memory
management, you need to balance this retain with a release. Example 1-10 shows the release performed in the
Song class’s
dealloc method.
- (void)dealloc {
[title release];
[super dealloc];
}This provides proper balance in the reference counting mechanism.
Warning
You should never call the dealloc method yourself.
Always let the memory management methods do it.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access