What happens if we do not check if (self) in the init methods?

I began to study the code made by our senior, I found that the init method always has code -(id)init. They used the code with the following methods. The code below is used for all viewControllers.

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

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

    //And in some viewcontroller contains.
    self = [super initWithNibName:@"ViewController" bundle:[NSBundle mainBundle]];
    if (self) {
        //Do some stuff
    }
    return self;
+4
source share
5 answers

When you access instance variables in your methods, the code is equivalent to addressing them through a self-pointer:

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

, - self- , ivars init, , . :

@implementation TestObj {
  int a;
}

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

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

, [super init] - , , - , .

+3

, :

if (self) {
   //Do some stuff
}
return self;

, .

// Do some stuff

- , self, return self.

+2

if (self) , super . - , , .

, init , , . init , super, Apple, , init, UIViewController.

, , init (self).

+2

, [super initWith...] , self, , .

self, .

if (self) "" if (self != nil), , , , if , 0 (null).

+1

if(self) , - 'self', - .

self - , , , self undefined if(self) false, .

-1

Source: https://habr.com/ru/post/1533148/


All Articles