O'Reilly logo

Objective-C Pocket Reference by Andrew Duncan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required