Objective-C 引用计数和自动释放

标签 objective-c memory-management

大家好,假设下面的代码:

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;
}

矩形的原点被声明为(保留)合成属性。 只是想知道两件事:

  1. 为什么在使用 Rectangle 的 origin 的 getter 访问器时 ref count 变为 3?我做错了什么吗?
  2. 引用计数为 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/

相关文章:

objective-c - UISearchDisplayController 与 ViewController 问题

ios - Objective-C解析Json并检查响应是否是对象数组中的单个对象

delphi - 如何解决内存分段并强制FastMM释放内存给OS?

c# - 在 C# 中使用 ArrayPool 重用从字符串到字节数组转换的内存?

objective-c - UIToolbar 在 iOS 7 中不是半透明的

objective-c - cocoa +自动化: service to generate text files not working

使用 malloc 为结构体分配 C 内存

ios - MKMapView 的内存使用率很高

memory-management - 将指针设置为 nil 以防止 Golang 中的内存泄漏

iphone - 混合 HTML/Objective-C iphone 应用程序的优点/缺点