O'Reilly logo

Beginning Mac OS® X Programming by Drew McCormack, Michael Trent

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

7.10. Memory Management

Memory is managed in Objective-C/Cocoa using a scheme known as reference counting. Basically, the NSObject class contains an integer instance variable that keeps track of how many entities in the program are using a given object. When the integer, which is known as the retain count, drops to zero, the object is not needed anymore, and the dealloc method is called to delete it.

When you initialize an object, it is given a retain count of 1. If you take no further action, the object will remain in existence for the lifetime of the program. You indicate that an object is not needed by sending it a release message, which reduces the retain count by 1. If the retain count drops to 0, the object is deallocated.

You can also explicitly indicate that an object should remain in existence by sending it a retain message, which increases the retain count by 1. retain is used when a part of your code needs to ensure that an object instantiated elsewhere remains in existence.

In the same way that objects have a retain count of 1 when they are first initialized, they also have a retain count of 1 when they are copied using the NSObject method copy, or a similar method like copyWithZone: or mutableCopy. Any copy method produces an object with a retain count of 1.

In some cases you can't release an object, even if you do not need it anymore. One such case is when the object must be returned from a method or function. If you invoke release, the object may get deallocated, ...

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