Memory Management
To properly manage memory, Cocoa
provides a reference
counting
mechanism, supported by the
NSObject and NSAutoreleasePool
classes. As its name suggests, reference counting maintains a count
of how many references there are to an object—indicating how
many other objects are interested in keeping the object around.
Reference counting is not automatic; the compiler has no way to
determine an object’s lifetime. Therefore, the
following NSObject reference counting methods must
be called to indicate the level of interest in an object to the
memory management system:
-
retain Increments the object’s reference count by
1. When you want to register interest in an object that you did not create or copy, indicate interest in it by calling this method.-
release Decrements the object’s reference count by
1. This message is sent to objects created with theallocmethod or sent aretainmessage when you are no longer interested in using them. If this causes the retain count to reach0, the runtime deallocates the object.-
autorelease Adds the object to the current autorelease pool . This allows you to release your interest in an object without immediately causing the retain count to reach
0. When the autorelease pool is itself released, it sends thereleasemessage to every object it contains. This is most useful when you want to pass the object to another object as a return value and won’t have the opportunity to release the object later by yourself.
The following set of rules will ...
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