Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

[self release], [self dealloc] or [super dealloc] in init methods?

I've just been reading up on how to properly fail in an init method and the docs seem to disagree with each other. One recommends throwing an exception while the others recommend cleaning up and returning nil. What's the current best practice here?

like image 995
Kevin Avatar asked May 25 '09 16:05

Kevin


1 Answers

I believe that the generally accepted practice is to return nil on failure. But you do want to release self to avoid a leak:

-(id)init
{
  if (self = [super init]) {
    ...
    if (thingsWentWrong) {
      [self release];
      return nil;
    }
    ...
  }
  return self;
}
like image 65
n8gray Avatar answered Sep 19 '22 05:09

n8gray