I am not a fan of the following construction
if (self = [super init])
{
//do something with self assuming it has been created
}
Is the following equivalent?
self = [super开发者_运维百科 init];
if (self != nil)
{
//Do something with Self
}
Yes they are. The = operator returns the value.
You may also wish to refer to Wil Shipley's take on this in his "self = [stupid init];" post. He originally recommended
- (id)init;
{
if (![super init])
return nil;
[...initialize my stuff...]
return self;
}
but demonstrates a handful of cases where this may fail currently and may not work with some future changes by Apple. He now recommends
- (id)init;
{
if (!(self = [super init]))
return nil;
// other stuff
return self;
}
Lars D has your answer, but if you are looking for a way to clean up your init
methods, I prefer the following:
- (id)init
{
if ((self = [super init]) == nil) { return nil; }
// your logic
return self;
}
It crams all of the unpleasantness into one line, and it leaves the rest of your method free of one if
statement (and associated parentheses).
精彩评论