我应该总是释放自己失败的init方法? [英] Should I always release self for failed init methods?

查看:115
本文介绍了我应该总是释放自己失败的init方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该总是在init里面发生故障时释放自我,或者如果我先初始化了实例变量,我应该怎么做?

Should I always release self when there is a failure inside init, or should I only do so if I have initialized instance variables first?

,这个模式有效吗?有没有时间,我不应该在init方法中释放self,或者我应该假设如果控制流进入init,self至少有一个保留计数1?

To put it another way, is this pattern valid? Is there a time when I shouldn't release self inside an init method, or should I assume that if the control flow enters init, self has at least a retain count of 1?

- (id)init
{
 if ((self = [super init]) == nil)
 {
  [self release];
  return nil;
 }

 //do some init stuff
 if (somethingFailed)
 {
  [self release];
  return nil;
 }
 return self;
}


推荐答案

你的初始化方法失败,那么你应该释放 self 。注意,如果 [super init] 返回 nil ,发送发布到 self as self nil 。这实际上是苹果所皱眉的:

If some check you need in your initialization method fails, then yes you should release self. Note however, that if [super init] returns nil it does not make sense to send release to self as self is nil. This is actually frowned on by Apple:


你应该只调用 [self release] 在故障点。如果从调用超类的初始化器得到 nil ,你不应该调用 release

You should only call [self release] at the point of failure. If you get nil back from an invocation of the superclass’s initializer, you should not also call release.

示例:

- (id)init
{
   self = [super init];
   if(self) {
       // do some init stuff

       if (somethingFailed)
       {
          [self release]
          self = nil;
       }
   }

   return self;
}

另请参阅Mac开发中心文档处理初始化失败

Also see the Mac Dev Center documentation on Handling Initialization Failure

这篇关于我应该总是释放自己失败的init方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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