Ray's playground

 

Memory Management(Chapter 4 of Cocoa Programming for Mac OS X)

  If you are using the garbage collector, it is important that you not keep references to objects that you don't care about. In the main function of lottery, you should set the now and array pointers to nil when you lose interest in them.
 1 // Done with 'now'
 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:

1 - (void)setFoo:(NSCalendarDate *)x
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. 

  The second idiom is: Check Before Change:
1 - (void)setFoo:(NSCalendarDate *)x
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: 

1 - (void)setFoo:(NSCalendarDate *)x
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.

posted on 2011-01-08 14:24  Ray Z  阅读(205)  评论(0编辑  收藏  举报

导航