Rules of thumb
Autorelease
Every time you have [[NSObject alloc] init]
you wrap it into an autorelease
:
// make sure it gets properly released
// autorelease releases the object at a later time.
NSObject *instance = [[[NSObject alloc] init] autorelease];
Things like this (can't remember the term) are always autoreleased, you should create your classes to correspond to this rule too:
NSString *test = [NSString stringWithFormat:@"%i", 4];
Retain / Release
If you need to store an object for longer than the current method retain it:
[instance retain];
If you don't need it anymore or exchanged it with another object:
[instance release];
You should always have the same amount of retains
as releases
in your code.
Accessors
Objective-C 2.0 let's you declare properties and writes your accessors for you. For example @property(retain, readwrite) NSString *text;
looks something like this:
- (NSString *)text {
return text; // I don't like calling variables _test
}
- (void)setText:(NSString *)newText {
[newText retain];
[text release];
text = newText;
}
init / dealloc
In those methods you should always use [self setVariable:…]
like this:
- (id)init {
if (self = [super init]) {
[self setText:@"Lorem ipsum dolor sit amet."];
// …
}
return self;
}
- (void)dealloc {
// make sure text is set to nil and the old value gets released.
[self setText:nil];
}
Garbage Collector
Use the Garbage Collector built into Objective-C 2.0, there's little gain from not using it if you can.
How does this retain / release work anyway?
Every time you allocate an object1, [NSObject alloc]
, the retain count is set to 1. If this count reaches 0 the object is deleted. [instance retain]
increases the count by 1 and [instance release]
decreases the count by 1.
1 [instance copy]
does allocate a new instance too, and therefore also has a retain count of 1.