为什么我不应该使用getter来释放objective-c中的属性? [英] Why shouldn't I use the getter to release a property in objective-c?

查看:62
本文介绍了为什么我不应该使用getter来释放objective-c中的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

同伴StackOverflow告诉我用户我在发布属性时不应使用getter方法:

  @property(nonatmic,retain)类型*变量; 
@synthesize变量;

//错误
[self.variable release];

//右
[变量发布];

他没有详细解释原因。他们对我来说是一样的。 我的iOS书籍说房产的吸气器将如下所示:

   - (id)变量{
返回变量;
}

所以这不是指 [自变量] self.variable 变量都是一样的?

解决方案

典型的getter看起来更像这样:

   - (id)变量{
return [[variable retain] autorelease];
}

所以如果你使用 [self.variable release] 你还有一个额外的保留 autorelease 当你刚才不需要的时候想要释放该对象并导致该对象在必要时间之后被释放(当自动释放池被耗尽时)。



通常,你要么使用 self.variable = nil 这样做的好处是它还将变量设置为 nil (避免由于悬空指针导致的崩溃),或者 [variable release] 这是最快的,如果你的setter有自定义逻辑,可能更适合 dealloc 方法。 / p>

I was told by a fellow StackOverflow user that I should not use the getter method when releasing a property:

@property(nonatmic, retain) Type* variable;
@synthesize variable;

// wrong
[self.variable release]; 

// right
[variable release]; 

He did not explain in detail why. They appear the same to me. My iOS book said the getter on a property will look like this:

- (id)variable {
    return variable;
}

So doesn't this mean [self variable], self.variable, and variable are all the same?

解决方案

A typical getter will look more like this:

- (id)variable {
   return [[variable retain] autorelease];
}

So if you use [self.variable release] you have an additional retain and autorelease that you don't really need when you just want to release the object and that cause the object to be released later than necessary (when the autorelease pool is drained).

Typically, you would either use self.variable = nil which has the benefit that it also sets the variable to nil (avoiding crashes due to dangling pointers), or [variable release] which is the fastest and may be more appropriate in a dealloc method if your setter has custom logic.

这篇关于为什么我不应该使用getter来释放objective-c中的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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