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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With