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.
转载于:https://www.cnblogs.com/zhtf2014/archive/2011/01/08/1930626.html
相关资源:Programming in Objective-C, 6th Edition