views:

111

answers:

3

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
 }
+6  A: 

Yes they are. The = operator returns the value.

Lars D
A: 

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).

e.James
I come from a Delphi background so I find the mixing of an assignment operator and an equals operator in an if statement overly confusing, which is why I was trying to move it out of the if statement.
Toby Allen
Fair enough. You could still do this in two lines: `self = [super init];` `if (self == nil) { return nil; }` but it's only worth it if that `if (self != nil) { ... }` block annoys you as much as it annoys me :)
e.James
+1  A: 

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;
}
Brad Larson