Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if we don't check for "if (self)" in init methods? [duplicate]

I started to look into the code done by our senior, I found the init method always have code -(id)init method. They used the code with the following ways. The code below is used for all viewControllers.

    self = [super initWithNibName:@"ViewController" bundle:[NSBundle mainBundle]];
    return self;

What is the use of the if(self) and self in this part?

    //And in some viewcontroller contains.
    self = [super initWithNibName:@"ViewController" bundle:[NSBundle mainBundle]];
    if (self) {
        //Do some stuff
    }
    return self;
like image 647
iniyan Avatar asked Mar 20 '23 02:03

iniyan


1 Answers

When you access instance variables in your methods the code is equivalent to addressing them via self pointer:

- (void)method {
  iVar = 1;
  // actually the following line will be executed:
  self->iVar = 1;
}

So if for some reason self pointer is nil and you access your ivars in init method, your application will crash as you will try to derefenrence null pointer. e.g. the following simple example will crash:

@implementation TestObj {
  int a;
}

- (id) init {
  self = [super init];
  self = nil;

  a = 1; // Crash
  return self;
}
@end

Also if your [super init] method returned nil for any reason, that might be indicator that something went wrong and you should not proceed with object initialization and any other required work with it.

like image 145
Vladimir Avatar answered Apr 02 '23 12:04

Vladimir