As part of first article we learned about object ownership. So how does the operating system keep track whether an object needs to be released or not? It is done using reference counting  mechanism– retainCount of each object.(Apple suggests us not to use reatinCount to directly make any decision regarding memory management). Each object in Cocoa has retainCount as a property.

Lets see what happens to retainCount of an object when you do some actions that have impact on retainCount:

  • When you create an object(new or alloc, copy or mutablecopy), it has a retain count of 1.
  • When you send an object a retain message, its retain count is incremented by 1.
  • When you send an object a release message, its retain count is decremented by 1.
  • When you send a autorelease message to an object, its retain count will be decremented by 1(not immediately as in case of release but some time in the future – We will discuss this in detail some time in future)

An object is deallocated when the retainCount reaches 0. Deallocation involves invocation of dealloc method of an object .(dealloc frees objects own memory and any other object holds).

And remember never to invoke dealloc method of an object.

Objects created with any method other than new, alloc, copy , mutablecopy, have a retain count of one but will be autoreleased. If you need to keep them in memory, you need to explicitly retain them.

NSString *stringObject = [[NSString alloc] init]; // retain count incremented by 1

[stringObject retain]; // retain count incremented by 1

[stringObject release]; // retain count decremented by 1

[stringObject autorelease]; // retain count will be decremented by 1, not guaranteed to happen //immediately as in case of release

So lets wind up the discussion at this state and will meet in next article.

Advertisements