Objective-C 属性和内存管理 [英] Objective-C Properties and Memory Management

查看:55
本文介绍了Objective-C 属性和内存管理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下属性定义:

@property (nonatomic,retain) MyObject* foo;

以下代码是否导致内存泄漏:

does the following code cause a memory leak:

self.foo = [[MyObject alloc] init];

?

看起来 alloc 调用将对象上的保留计数增加到 1,然后属性设置器中的保留将其增加到 1.但是由于初始计数从未减少到 0,因此即使在 self被释放.这种分析是否正确?

It looks like the alloc call increments the retain count on the object to 1, then the retain inside the property setter increases it to 1. But since the initial count is never decremented to 0, the object will stick around even when self is released. Is that analysis correct?

如果是这样,看起来我有两个选择:

If so, it looks like I have two alternatives:

self.foo = [[[MyObject alloc] init] autorelease];

出于性能原因不推荐在 iPhone 上使用,或者:

which is not recommended on the iPhone for performance reasons, or:

MyObject* x = [[MyObject alloc] init];
self.foo = x
[x release];

有点麻烦.还有其他选择吗?

which is a bit cumbersome. Are there other alternatives?

推荐答案

你说得对,self.foo = [[MyObject alloc] init]; 正在泄漏内存.两种选择都是正确的,可以使用.关于 autorelease 在这样的声明中:请记住,一旦当前运行循环结束,该对象将被自动释放池释放,但它很可能会被 保留更长的时间self,所以这里不会出现内存使用高峰的问题.

You are right, self.foo = [[MyObject alloc] init]; is leaking memory. Both alternatives are correct and can be used. Regarding the autorelease in such a statement: keep in mind that the object will released by the autorelease pool as soon as the current run loop ends, but it will most probably be retained a lot longer by self, so there is no issue with memory usage spikes here.

这篇关于Objective-C 属性和内存管理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆