摘自《在 Mac 上学习 Objective-C(第二版)》一书。为什么retain count
在以下代码块中是 2 而不是 1:-
- (void) setEngine: (Engine *) newEngine
{
[engine release];
engine = [newEngine retain];
// More BAD CODE: do not steal. Fixed version below.
} // setEngine
some_function
{
Engine *engine = [Engine new]; // count: 1
Car *car1 = [Car new];
Car *car2 = [Car new];
[car1 setEngine: engine]; // count: 2 But why? 1-1=0 (due to [engine release]
// in -(void) SetEngine.
// and after engine=[newEngine retain] retain count is 1.
[engine release]; // count 1
[car2 setEngine: [car1 engine]]; // oops!
return 0;
}