Friday, October 2, 2009

IPhone development: memory management rules

Right now I am learning the IPhone development using objective-C, I have to admit that I am a new beginner of objective-C, even if I have lots of experience of C/C++ development, the syntax of object-C confuse me a lot.

Right now I run into a problem: when should we release the object? Here is the example:

YellowViewController *yellowController =
[ [YellowViewController alloc] initWithNibName:@"YellowView"
self.yellowViewController = yellowController;
[yellowController release];

It seems an idiom for objective-c memory management, since I’ve seen lots of source code did in the similar way. I was really confused, since I treated the objective-c object as a c++ pointer. In the above example, yellowController and self.yellowViewController are pointers, they are pointing to the same memory address, if we release yellowController, then how about self.yellowViewController? Will it become an invalid object because it is pointing to the memory address which was released already?

Through me research, then I understand the memory management rule of objective-c. It uses reference counting method to manage the memory:
- When create an object using alloc, the reference count will be 1;
- When release method is called, decreases reference counter by 1;
- When copy or retain method is called, increases the reference counter by 1;

Then I have a question: how about the assignment operation? What does it exactly do? Will it increase the reference counter or will it copy the whole object data to the variable self.yellowViewController?

Finally I realize that the key is in the definition of the instance variable self.yellowViewController:
It’s definition is like this:
@property (retain, nonatomic) YellowViewController *yellowViewController;

Which means we do the assignment operation to the class variable self.yellowViewController, the retain method will be called, which means the reference counter will be increased by 1.

We can use the following methods to check the reference counter:
NSLog([NSString stringWithFormat:@"%u", [yellowController retainCount]]);
self. yellowViewController = yellowController;
NSLog([NSString stringWithFormat:@"%u", [yellowController retainCount]]);

In summary, here is the simple rules for object-c memory management:

Retention Count rules: (copy from here)
1. Within a given block, the use of -copy, -alloc and -retain should equal the use of -release and -autorelease.
2. Objects created using convenience constructors (e.g. NSString's stringWithString) are considered autoreleased.
3. Implement a -dealloc method to release the instance variables you own

Some good references:
1. Very simple rules for memory management in Cocoa
2. Learn Objective-C
3. Forum thread: newbie memory management question ("release")

No comments:

Post a Comment