使用访问器将属性设置为新分配的对象会导致内存泄漏 [英] Setting property to newly alloc'd object using accessor cause memory leak
问题描述
我只想确认以下内容是否引起内存泄漏.
I just want confirmation on whether or not the following causes a memory leak.
.h文件
@property (nonatomic, retain) MyObject *foo;
.m文件
@synthesize foo;
...
self.foo = [[MyObject alloc] init];
dealloc
设置为
[foo release];
我的理解是,自动生成的访问器方法的实现看起来像
My understanding is that the implementation of the auto-generated accessor method looks like
-(void)setFoo:(MyObject *)newObject {
if (foo != newObject) {
[foo release];
foo = [newObject retain];
}
}
现在遍历self.foo = [[MyObject alloc] init];
对我来说是,分配了一个新的MyObject对象,其保留计数为1,将其传递给setFoo:
,由于新分配的foo永远不会等于myObject,因此释放旧值,增加newObject的保留计数使其为 2 并将其分配给foo"
Walking through self.foo = [[MyObject alloc] init];
now reads to me as, "allocated a new MyObject object whose retain count will be 1, pass it to setFoo:
, foo will never be equal to myObject as it was newly allocated, so release the old value, increment the retain count of newObject making it 2 and assign it to foo"
dealloc释放foo,因此将其保留计数设置为 1 ,这意味着该对象已泄漏?
dealloc releases foo therefore setting its retain count to 1, which means this object is leaked?
要安全地执行此操作,我们应该像这样编写代码
To do this safely we should write our code like
self.foo = [[[MyObject alloc] init] autorelease];
我的理解正确吗?
编辑
我意识到这个问题并不真正适合SO,因此请随时将我指向一个更好的地方来提出此类问题.
I realize this question is not really appropriate for SO, so feel free to point me to a better place to ask this type of question as well.
推荐答案
是的,那是绝对正确的.
Yes, that is absolutely correct.
这篇关于使用访问器将属性设置为新分配的对象会导致内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!