Saturday, October 30, 2010

An Introduction to Memory Management in Objective-C pt.1

Hello everyone! This is my first post on this blog and I hope you enjoy it.

On this post I will introduce the concepts behind memory management in Objective-C. This will be the first of a serie of posts about memory management, where I intend to cover everything you need to know to be confident with pointers in Objective-C. :)


To understand memory allocation in Objective-C, we must first understand Ownership. Ownership principle states that for each object one creates, one is the only responsible for destroying it. If one doesn't destroy it, then there will be a memory leak. And if someone else destroys it, then there will be bugs, crashes and all sorts of unexpected behaviors due to invalid references being used.

In practice, the Ownership principle states that for each new there should be a delete on a C++ code, for example.

This principle is implemented on compilers via reference counting. For each allocator call, the reference count of an object is incremented and for each destructor call this reference count is decremented. When the reference count reaches 0, the memory space is cleared and set as available for other allocations.

In Objective-C, there are 4 keywords for allocators: alloc, new, copy, retain and 2 for destructors: release and autorelease.

I will explain each one on the next post.

Stay tuned for more!

No comments:

Post a Comment