大家好,假设下面的代码:
int main (int argc, const char * argv[])
{
//[...]
Rectangle* myRect = [[Rectangle alloc] init];
Vector2* newOrigin = [[[Vector2 alloc] init] autorelease]; // ref count 1
[newOrigin setX: 50.0f];
[myRect setOrigin: newOrigin]; // ref count 2
[myRect.origin setXY: 25.0f :100.0f]; // ref count goes to 3... why ?
[myRect release];
[pool drain];
return 0;
}
矩形的原点被声明为(保留)合成属性。 只是想知道两件事:
- 为什么在使用 Rectangle 的 origin 的 getter 访问器时 ref count 变为 3?我做错了什么吗?
- 引用计数为 3,我不明白这段代码如何不能泄漏。在 myRect 上调用 release 将使它下降到 2,因为我在 dealloc() 中调用了 origin 上的 release。但是,autorelease 什么时候生效呢?
谢谢!
最佳答案
Why does ref count goes to 3 when using the getter accessor of Rectangle's origin?
因为您的@property 被声明为atomic
(默认值),因此合成的 getter 会保留并自动释放返回值。
Am I doing something wrong ?
是的。您正在研究绝对保留计数。
任何对象的绝对保留计数是完全没有用的。你只关心增量;如果您导致保留计数增加,则必须使其减少。
With a ref count of 3, I don't understand how this snippet of code cannot leak. Calling release on myRect will make it go down to 2 since I call release on the origin in dealloc(). But then, when does autorelease take effect?
autorelease
只是一个延迟的release
,它在包含池被drain
时启动。因此,在您的情况下,对象将在执行 [pool drain];
时被释放。
关于Objective-C 引用计数和自动释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3058828/