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

查看:16
本文介绍了为什么自实现的 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 应该保留并自动释放返回的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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