Tutorial :What does 'release' means in this situation on iPhone?


I want to ask a stupid question about the iPhone application. I am the green of the iPhone app. I read the following code in the Apple website.

    MyViewController *aViewController = [[MyViewController alloc] initWithNibName:@"MyViewController" bundle:[NSBundle mainBundle]];      [self setMyViewController:aViewController];      [aViewController release];  

And I have a question, how it means of the 'release' in the line 3?

Does it presents the memory clear? or the program take control of that object? or other meanings. Thank you very much.


When you alloc something, the object you get will have a retain count of 1 - this means that this object is currently being used by someone, so it should not be removed from memory. If you call retain on an object it will increase the retain count, meaning the object is being used by 2 things. If the retain count reaches 0, it implies that the object is no longer being used by anything and it can be removed from memory. You can decrease an object's retain count by calling release on the object.

In your example, aViewController is alloc'd and after line 1 has a retain count of +1.

It is then set as the view controller in line 2. This method is therefor taking ownership of the object, so should retain it for its own use.

Line 3, we don't want anything more to do with the view controller, so we release our hold of it. The retain count decreases by one - and it is now up to the new owner to release it when it is finished with it.

You might find it helpful to read through the memory management section of this tutrial


Whenever you call alloc, you own a reference to the object that comes back, and you must call release to indicate that you no longer intend to use that reference.

In the above case, you have allocated a new view controller and assigned it to a property of your class. Assuming the property is declared with the retain option, the property will acquire its own reference to the view controller by called retain on it. So there are now two active references to it. The property will eventually release its reference (either when it is assigned a different view controller, or when your class is finalised). But if you don't call release yourself, one reference will remain, and the view controller will never be freed.

In short, you must match every alloc with a release, otherwise things will leak.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »