Skip to content

Introduction to Memory Management on iPhone

December 5, 2010

Content of this Article:

>Memory Management Model.

>How to allocate, retain and release Objects in Memory.

>Using nil to safe release Objects.

>References.

Memory Management Model in iOS dosen’t have a Garbage Collector inorder to increase the performance of the language on the mobile platform which is constrained to small computational power. Forthat it uses Reference Counting the idea of Reference Couting is very simple every object you define in the memory have a number that counts how many items reference this object, When it reaches zero the object is deallocated from the memory since no other object needs it.

Let’s take it to the Next Step Memory Allocation, to allocate an object we will use the keyword “alloc” and then call “init” to initialize the object, for Example:

NSString *string_1 = [[NSString alloc] init];

Now the reference count of the object is “1”, since alloc will allocate a memory block and makes it’s reference count to “1”. if another object referenced the same object the reference count wil increase by “1” (current reference count = 2) :

NSString *string_2 = [string_1 retain];

But after doing all these alloc and retain operations we are going to be faced with a huge problem which is Memory Leaks, objects tha aren’t needed or out of our scope will resides in the memory and won’t be garbage collected, Why ? Because there reference count isn’t “0”. Calling “release” every time on an object will decrease the reference count of the object by one.

[string_1 release]; //now reference count is “1”.

[string_1 release]; //now reference count is “0”, and the object will be deallocated.

since “nil” can be retained or released, by using this great advantage you can define a setter for your variable which will realese your object and assign it to nil. Why is that even useful ? It’s very helpful to not fail in an invalid pointer operation, for example:

-(void) setStr:(NSString *) input{
[input retain];
[myStr release];
myStr = input;
}

-(void) callFunction:(id)sender {
if(myStr)
//do something …..
else
//pointer assigned to null can't do anything …..
}

-(void) dealloc {
[self setStr:nil];
[super release];
}


References:

Learning iPhone Programming

- Memory Management Basics Tutorial Video by Mark

Advertisement

From → Objective-C

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.