何时释放实例变量 [英] When to release an instance variable

查看:98
本文介绍了何时释放实例变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我有这种情况:

  //在接口标头
@property(nonatomic,retain )OtherClass * otherClass;

//实现
- (id)initWithOtherClassInstance:(OtherClass *)otherClass
{
if(self!= [super init])
return自;

self.otherClass = otherClass;

return self;
}

- (void)dealloc
{
//我需要发布otherClass吗?
[otherClass release];

[super dealloc];
}



我想知道是否应该释放一个实例变量, ,新的还是复制被调用?内存管理指南说我不知道​​,但我担心的是 self.otherClass = otherClass 将保留实例变量,从而导致泄漏,当我决定

此外,在方法中释放实例变量, dealloc 方法不会生成异常,这会在它被过度使用的情况下。



我的推理在这里是否有意义,在这样的情况下,最好的办法是什么?

解决方案

是的,你需要释放这,其他答案建议。但是我发现在通过属性设置保留的ivar上显式调用 [foo release] 有点不平衡。我更喜欢在这些情况下设置 self.otherClass = nil;

code>。



当然,释放你,但它只是看起来更平衡和干净。


Basically I have this scenario going on:

//in interface header 
@property(nonatomic,retain)OtherClass *otherClass;

//implementation
- (id)initWithOtherClassInstance:(OtherClass*)otherClass
{ 
    if (self != [super init])
        return self;

         self.otherClass = otherClass;

    return self;
}

- (void)dealloc
{
    //Do I need to release otherClass ?
    [otherClass release];

    [super dealloc];
}

I'm wondering whether I should release an instance variable on which not explicitly alloc, new or copy was called? The memory management guides say I shoud not, but what I'm worrying about is that self.otherClass = otherClass would retain the instance variable and thus cause a leak when I would decide to not release it in the dealloc method.

Moreover releasing the instance variable in the dealloc method does not generate an exception, which it would in case it was overreleased.

Does my reasoning here make any sense, and what is the best thing to do in a case like this ?

解决方案

Yes you do need to release this, as other answers suggest. But I find that explicitly calling [foo release] on an ivar that you retained via property setter to be a little unbalanced. I prefer setting self.otherClass = nil; in these scenarios.

Of course under the hood it will do a release for you, but it just looks more balanced and clean.

这篇关于何时释放实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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