为什么一个自我实现的getter保留和自动释放返回的对象? [英] Why should a self-implemented getter retain and autorelease the returned object?

查看:131
本文介绍了为什么一个自我实现的getter保留和自动释放返回的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例:

- (NSString*) title {
    return [[title retain] autorelease];
}

设置实际上保留了它,对吧?实际上没有人应该绕过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保留和自动释放返回的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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