Memory Management
The liveness of an object—whether or not it is referenced by other objects currently in use—is inherently a global property. This means that keeping track of object usage tempts you to breach the encapsulation and modularity of your program. There are several approaches you can use with Objective-C to help manage object lifecycles:
Manual memory management, using the free functions provided by the Objective-C runtime
Semi-automatic memory management, using root class reference-counting methods
Automatic memory management, using third-party garbage collector tools
The programming tools and libraries you use may constrain you toward or away from some strategies. For example, the Cocoa class library uses reference counting; if your code uses Cocoa objects it will have to be written to manage those objects with reference counting, even if your own objects use a different mechanism.
Manual Memory Management
You can explicitly release the memory held by an object by calling its
-free
method (if it inherits from Object
) or its -dealloc
method (if it inherits from NSObject
). It will be your responsibility to
ensure that your program no longer needs the object.
In classes you write, the deallocation method should release any objects managed by the receiver, as well as any other kinds of resources (such as network sockets) the receiver holds. As with deciding to deallocate the receiver itself, it is your responsibility to ensure that your program no longer needs the objects the ...
Get Objective-C Pocket Reference now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.