使用访问器将属性设置为新分配的对象会导致内存泄漏
我只是想确认以下是否会导致内存泄漏。
.h 文件
@property (nonatomic, retain) MyObject *foo;
.m 文件
@synthesize foo;
...
self.foo = [[MyObject alloc] init];
dealloc
设置为
[foo release];
我的理解是,自动生成的访问器方法的实现看起来像
-(void)setFoo:(MyObject *)newObject {
if (foo != newObject) {
[foo release];
foo = [newObject retain];
}
}
遍历 self.foo = [[MyObject alloc] init];< /code> 现在对我来说是这样的:“分配了一个新的 MyObject 对象,其保留计数将为 1,将其传递给
setFoo:
,foo 永远不会等于新分配的 myObject,因此释放旧值,增加newObject的保留计数,使其2并将其分配给foo”
dealloc释放foo,因此将其保留计数设置为1,这意味着该对象被泄漏?
为了安全地做到这一点,我们应该编写我们的代码,比如
self.foo = [[[MyObject alloc] init] autorelease];
我的理解正确吗?
编辑
我意识到这个问题不太适合SO,所以请随时向我指出一个更好的地方来问此类问题。
I just want confirmation on whether or not the following causes a memory leak.
.h file
@property (nonatomic, retain) MyObject *foo;
.m file
@synthesize foo;
...
self.foo = [[MyObject alloc] init];
dealloc
is setup as
[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];
}
}
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 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];
Is my understanding correct?
EDIT
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,这是绝对正确的。
Yes, that is absolutely correct.
你可以这么做。或者,由于我们知道设置器会自动保留,因此我们可以执行以下操作而不是自动释放:
您选择的可能是编码风格的问题。如果您想掌握使用 self.foo 的窍门,那么为了一致性和错误修复,请务必使用您的方法。如果您习惯使用点语法,请使用后者。
you could do that. Alternatively, since we know the setter automatically retains, we could do the following rather than autorelease:
Which you choose may be a matter of coding style. If you are trying to get the hang of using self.foo, then by all means use your method for the sake of consistency and bug fixing. If you are comfortable with using the dot syntax then use the latter.
还有另一个常见的模式:
And another common pattern: