Objective-C’s memory management uses allocation of memory and deallocation, similar to C’s malloc/free mechanism. Objective-C makes use of alloc/dealloc. However, it is more complex than that. Every NSObject has a “retain” count. Where alloc’ing sets the retain count to 1 for that object. What is interesting, is as a user you should never call “dealloc” directly. This is because Objective C will dealloc the object automatically when it’s retain count reaches 0. How would a retain count reach 0? When you are done with the object, you should call “release”.
This also means that if you are working on an instance of an object, you are responsible for managing its memory. I.e. you never know when that instance that was passed to you will have release called on it, causing your copy to be a invalid reference. So, if you have a method that takes an object and uses it for awhile (setting it to an instance variable, for example), you should retain it, and release it when you are finished.
You’ll see this paradigm used throughout the UI Toolkit. For example,
MyView *view = [[MyView alloc] initWithFrame:[window frame]];
[window addSubview:view];
[view release];
You’ll notice that as a client, I create a view and add it to a window view. That is the extent of what I need it for, so, therefore, release it. If the window’s addSubview method did not retain it, that view would be destroyed. Therefore, reading the documentation of NSView, you can see:
addSubview:
Adds a view to the receiver’s subviews so it’s displayed above its siblings.
- (void)addSubview:(NSView *)aView
Parameters
aView
The view to add to the receiver as a subview.
Discussion
This method also sets the receiver as the next responder of aView.
The receiver retains aView. If you use removeFromSuperview to remove aView from the view hierarchy, aView is released. If you want to keep using aView after removing it from the view hierarchy (if, for example, you are swapping through a number of views), you must retain it before invoking removeFromSuperview.
Emphasis is mine, but you’ll see that it is retained.