Understand Reference Counting
How Reference Counting Works
Under reference-counting architectures, an object is assigned a counter to indicate how many things have an interest in keeping that object alive. A method to inspect the retain count, called retainCount, is generally not very useful, even when debugging, so I (and Apple) encourage you not to use it. The following three methods declared on the NSObject protocol can manipulate that counter to either increment it or decrement it:在reference-counting实现之前分配一个counter给对象来保持对象的存活,一个方法叫retainCount它通常是不好用的即使在debug的时候,所以鼓励你不使用它。下面这三个方法在 NSObject protocol里声明能控制counter加或者减。
- retain Increment the retain count.
- release Decrement the retain count.
- autorelease Decrement the retain count later, when the autorelease pool is drained.
features
A method to inspect the retain count, called retainCount, is generally not very useful, even when debugging, so I (and Apple) encourage you not to use it.一个方法叫retainCount它通常是不好用的即使在debug的时候,所以鼓励你不使用它。
Objects are said to own other objects if they hold a strong reference to them. This means that they have registered their interest in keeping them alive by retaining them.Objects是拥有其他的对象如果保持强引用它们。
In Objective-C, a call to alloc will result in the return of an object that is said to be owned by the caller. That is to say, the caller’s interest has already been registered because it used alloc.在Objective-C里面,调用alloc会返回一个对象,表示由调用方拥有,也可以说调用方的interest已经注册了因为它使用alloc。
However, it is important to note that this does not necessarily mean that the retain count is exactly. It might be more, since the implementation of either alloc or initWithInt: may mean that other retains have been made on the object. What is guaranteed, though, is that the retain count is at least.很重要的一点是这并不意味着保留retain count 是必要的,它可能更多的实现alloc或者initWithInt。 You should always think about retain counts in this way. You should never guarantee what a retain count is, only what effect your actions have had on the retain count: whether that is incremented or decremented.
Memory Management in Property Accessors
- (void)setFoo:(id)foo
{
[foo retain];
[_foo release];
_foo = foo;
}
The new value is retained, and the old value is released. Then the instance variable is updated to point to the new value.新的值被保留,旧的值被释放,然后更新实例变量以指向新的值。
Autorelease Pools
- (NSString*)stringValue
{
NSString *str = [[NSString alloc] initWithFormat:@"I am this: %@", self];
return [str autorelease];
}
Since the release from being in the autorelease pool won’t happen until next time around the event loop, So autorelease is a way of extending the lifetime of an object just enough so that it can survive across method call boundaries.因为在autorelease pool里面直到下一次事件循环release都不会发生,所以autorelease的方式只是用来延长对象的生存期确保它幸存的方法能被调用。