ios - What happens if we don't check for "if (self)" in init methods? -
this question has answer here:
i started code done our senior, found init method have code -(id)init
method. used code following ways. code below used viewcontrollers.
self = [super initwithnibname:@"viewcontroller" bundle:[nsbundle mainbundle]]; return self;
what use of if(self)
, self
in part?
//and in viewcontroller contains. self = [super initwithnibname:@"viewcontroller" bundle:[nsbundle mainbundle]]; if (self) { //do stuff } return self;
when access instance variables in methods code equivalent addressing them via self pointer:
- (void)method { ivar = 1; // following line executed: self->ivar = 1; }
so if reason self pointer nil , access ivars in init method, application crash try derefenrence null pointer. e.g. following simple example crash:
@implementation testobj { int a; } - (id) init { self = [super init]; self = nil; = 1; // crash return self; } @end
also if [super init] method returned nil reason, might indicator went wrong , should not proceed object initialization , other required work it.
Comments
Post a Comment