Why should a self-implemented getter retain and autorelease the returned object?(为什么自实现的 getter 应该保留并自动释放返回的对象?)
问题描述
例子:
- (NSString*) title {
return [[title retain] autorelease];
}
setter 实际上已经保留了它,对吧?实际上没有人应该绕过 Setter ......所以我想知道为什么 getter 不只是返回对象?它实际上已经保留了.或者如果同时另一个对象被传递给设置器,是否需要这样做?
The setter actually retained it already, right? and actually nobody should bypass the Setter... so I wonder why the getter not just returns the object? It's actually retained already. Or would this just be needed in case that in the mean time another objects gets passed to the setter?
推荐答案
从这里 http://www.macosxguru.net/article.php?story=20030713184140267
- (id)getMyInstance
{
return myInstanceVar ;
}
或
- (id)getMyInstance
{
return [[myInstanceVar retain] autorelease] ;
}
有什么区别?第二个允许调用者获取容器对象的实例变量,处置容器并继续使用实例变量直到当前自动释放池的下一次释放,而不会受到间接产生的实例变量释放的伤害通过释放其容器:
What's the difference ? The second one allows the caller to get an instance variable of a container object, dispose of the container and continue to play with the instance variable until the next release of the current autoreleased pool, without being hurt by the release of the instance variable indirectly generated by the release of its container:
aLocalVar = [aContainer getAnInstanceVar] ;
[aContainer release];
doSomething(aLocalVar);
如果get"是以第一种形式实现的,你应该写:
If the "get" is implemented in the first form, you should write:
aLocalVar = [[aContainer getAnInstanceVar] retain];
[aContainer release];
doSomething(aLocalVar);
[aLovalVar release];
第一种形式在代码执行速度方面效率更高一些.但是,如果您正在编写供他人使用的框架,也许应该推荐第二个版本:它使使用您的框架的人的生活更轻松:他们不必过多考虑自己在做什么……;)如果您选择第一个样式版本,请在文档中明确说明...无论您选择哪种方式,请记住从版本 1 更改为版本 2 是为了保存客户端代码,从版本 2 回到版本 1 会破坏现有客户端代码……
The first form is a little bit more efficent in term of code execution speed. However, if you are writing frameworks to be used by others, maybe the second version should be recommanded: it makes life a little bit easier to people using your framework: they don't have to think too much about what they are doing…;) If you choose the first style version, state it clearly in your documentation… Whatever way you will be choosing, remember that changing from version 1 to version 2 is save for client code, when going back from version 2 to version 1 will break existing client code…
这篇关于为什么自实现的 getter 应该保留并自动释放返回的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么自实现的 getter 应该保留并自动释放返回的对象?
基础教程推荐
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01