Memory Management(Chapter 4 of Cocoa Programming for Mac OS X)
2 now = nil;
3
4 for (LotteryEntry *entryToPrint in array) {
5 NSLog(@"%@", entryToPrint);
6 }
7 // Done with 'array'
8 array = nil;
9 [pool drain];
10 NSLog(@"GC = %@", [NSGarbageCollector defaultCollector]);
11 return 0;
12
Objects are added to the current autorelease pool when they are sent the message autorelease. When the autorelease pool is drained, it sends the message release to all objects in the pool.
There are three common idioms in setter methods.
The first idiom is: Retain, then Release:
2 {
3 [x retain];
4 [foo release];
5 foo = x;
6 }
Here, it is important to retain before releasing. Suppose that you reverse the order. If x and foo are both pointers to the same object that happens to have a retain count of 1, the release would cause the object to be deallocated before it was retained. Trade-off:If they are the same value, this method performs an unnecessary retain and release.
2 {
3 if (foo != x) {
4 [foo release];
5 foo = [x retain];
6 }
7 }
Here, you are not setting the variable unless a different value is passed in. Trade-off: An extra if statement is necessary.
The final idiom is: Autorelease Old Value:
2 {
3 [foo autorelease];
4 foo = [x retain];
5 }
Here, you autorelease the old value. Trade-off: An error in retain counts will result in a crash one event loop after the error. This behavior makes the bug harder to track down. In the first two idioms, your crash will happen closer to your error. Also, autorelease carries some performance overhead.