This is a mirror of official site: http://jasper-net.blogspot.com/

Manual Memory Management in Objective-C

| Tuesday, January 25, 2011
Objective-C on iOS has no garbage collector, so it is up to the programmer to make sure that memory is properly freed once an object is no longer needed. On the other hand, Objective-C on the Mac does have a garbage collector (in Objective C 2.0). This blog post focuses on how to manage memory in the absence of a garbage collector.

When managing memory manually, two major issues to watch out for are premature deallocation and memory leaks.

Cocoa Touch framework uses manual reference counting to manage memory on the iOS devices. Reference counting works on the principle that once created, every object has an owner. During its existence, its owner may change and it may even have more than one owners. When the number of owners for an object drops to zero, it deallocates itself to free up the memory being used.

retain & release:

Owners are tracked via retain counts. When an object is created it always has a retain count of 1. To own an object its retain count is incremented via the retain message. On the other hand, when the object is no longer needed its ownership is relinquished by decrementing the retain count via the release message. When the count reaches zero, the object sends itself the dealloc message and returns all the memory back to the heap.

autorelease:

autorelease marks an object for future release (delayed release). When an object is sent the autorelease message, its retain count is incremented and it is added to an instance of NSAutoreleasePool. The Autorelease pool keeps track of all the objects that have been sent the autorelease message. This pool is drained periodically, at which time all the objects within it are sent the release message.

Read more: Umair's Blog

Posted via email from Jasper-net

0 comments: