What is the difference beetween :
// 1
-(id) init {
self = [super init];
if (self) {
... do init ....
}
return self;
}
// 2 - I guess it's exactly the same as previous
-(id) init {
if (self = [super init]) {
... do init ....
}
return self;
}
// 3 - is this one a really bad idea and if yes, Why ?
-(id) init {
self = [super init];
if (!self) return nil;
... do init ....
return self;
}
// 4 - I think this one sounds OK, no ? But what is returned... nil ?
-(id) init {
self = [super init];
if (!self) return self;
... do init ....
return self;
}
EDIT : Added thanks to Peter M.
// 5 - I really like the readability of this one
-(id) init {
if(!(self = [super init])) return self; // or nil
... do init ....
return self;
}
==instead of=. You can block the warning by using another(...)around the expression, but it’s not easy to read.nilmakes the code easier to understand (maybe this is only my opinion, someone else can say 4 is better than 3).In summary: use 1 or 3. When initialization code is long, you should use 3 to avoid having most of method code in one
ifblock. Apple uses only 1 but don’t follow it blindly. Apple has no documented coding standards and sometimes what they recommend is very questionable.You can use 4 instead of 3 but don’t mix 3 & 4 in your code.