Should I always release self for failed init methods?

无人久伴 提交于 2019-12-05 00:44:22
Brandon Bodnar

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

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