Objective-C Memory Management


Regardless of what your language background is, memory management in Objective-C can be a bit difficult to get a handle on. I won’t claim to be an expert on the topic, since I’m still learning myself, but here’s a few of the things I’ve learned while trying to unravel the complexity lately:

There’s a seeming mass of various methods with which you can message NSObjects and any class object that is extend from NSObject, including: alloc, dealloc, retain, release, autorelease, and finalize. But just what do all these mean?

First of all, you need to know that Objective-C has garbage collection capability. If you don’t know what garbage collection is, do a Google Search and familiarize yourself with the topic. Once you’re familiar with the wonders of garbage collection, you need to know that Objective-C may not always use it…

So, as best as I can tell, here’s what the above methods do:

  • alloc: Allocates a block of memory the size necessary for a new instance of an object, returning an uninitialized instance of the object – the object should be initialized using a class initializer after being allocated.
  • dealloc: Automatically called when a block of memory is to be released – ONLY if garbage collection is NOT enabled. Classes should release – not dealloc any objects allocated by the object from here, as they should no longer be needed. Finally, subclasses should also call the superclass dealloc method. This method should NOT be called manually
  • retain: Increments a “retain” count for the object – if the retain count of an object is greater than zero, it will not be garbage collected, autoreleased, dealloced, or finalized in any case.
  • release: Decrements a “retain” count for the object – when the retain count of an object becomes zero, it is free to be garbage collected, autoreleased, and dealloced or finalized.
  • autorelease: Adds the object to the “innermost” autorelease pool; the object will be released when the autorelease pool schedules the next release. When the schedule autorelease occurs, the “retain” count will be decremented and the object removed from the autorelease pool. Calling autorelease multiple times will add the object to the autorelease pool multiple times, and thus call release the same number of times before the object is removed from the pool. If the “retain” count reached zero, the object will be dealloced.

That’s the ugly… Is general, things are actually quite simple:

1) If an object is created using alloc, it will have a retain count of 1, and should be released using release when the object is no longer needed.

2) Calling retain will increment the retain counter; release will need to be called the same number of times to bring the retain count to pre-retain state. (Excluding autorelease scenarios)


One response to “Objective-C Memory Management”

Leave a Reply

Your email address will not be published. Required fields are marked *