Objective-C: Retain, Release, Autorelease

The rules for -retain, -release, and -autorelease are simple. If you alloc, copy, or retain something, you also need to (eventually) release or autorelease it. If you don't do any of those three things, you don't need to do any memory management at all. Not only don't need to, if you try, it messes things up.

If you alloc something, it's just like you sent -retain to the object. So you release or autorelease it. If you do a copy or a mutableCopy, it's also the same as sending a retain. So you also release or autorelease it.

If you never sent a retain (or equivalent) method to an object, then by default it is autoreleased and will go away on its own. The following example doesn't need to be released explicitly since it has already been given an -autorelease message internally. (see NSArray Class Reference -> arrayWithObjects:)
NSArray * sampleList = [NSArray arrayWithObjects:@"One", @"Two", nil];

Also, in my code I always try to release an object instead of autoreleasing it as much as possible.

The actual mechanism here is that when you call -autorelease, a pointer to the object is added to a list kept by an NSAutoreleasePool. When that pool is deallocated, every object in the list gets a -release method. Thus -autorelease is a delayed -release.

Subclassing UIView with NIB file

Here's how UIView subclassing is done (with NIB files). I felt the need of doing so for two reasons: reusability and maintainability.

Header class:
#import <UIKit/UIKit.h>

@interface MyCustomView: UIView

+ (MyCustomView *)createWithOwner:(id)owner;

@end

Implementation class:
#import "MyCustomView.h"

@implementation MyCustomView

+ (MyCustomView *)createWithOwner:(id)owner {
  NSString *nibName = NSStringFromClass([self class]);
  NSArray *nib = [[NSBundle mainBundle] loadNibNamed:nibName owner:owner options:nil];
  MyCustomView *view = [nib objectAtIndex:0];
  return view;
}

@end

Using the the new class is as simple as this:
#import "MyCustomView.h"

...

MyCustomView * customView = [MyCustomView createWithOwner:self];
[self.view addSubView: customView];
[customView release];  

...

Related posts:

Bookmark and Share