Should I always release self for failed init methods?

随声附和 提交于 2019-12-22 03:42:13

问题


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?

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;
}

回答1:


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:

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.

Example:

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

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

   return self;
}

Also see the Mac Dev Center documentation on Handling Initialization Failure



来源:https://stackoverflow.com/questions/2467685/should-i-always-release-self-for-failed-init-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!