English 中文(简体)
Is this code Equivalent
原标题:

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





相关问题
How to change out-of-focus text selection color in Xcode?

Okay, I ll bite. I ve got really pleasant code/window colors set up in Xcode. Ordinarily, my selection color is very visible. When I am doing a project search and iterating through the results, ...

pdo database abstraction

Can someone help me to see what is going wrong with this setup I build the @sql query in the function below like this. The extra quotes are setup in the conditions array. $sql .= " WHERE $...

I wish I could correlate an "inline view"

I have a Patient table: PatientId Admitted --------- --------------- 1 d/m/yy hh:mm:ss 2 d/m/yy hh:mm:ss 3 d/m/yy hh:mm:ss I have a PatientMeasurement table (0 to ...

Syntax help! Php and MYSQL

Original: $sql = "SELECT DATE(TimeAdded) AS Date, $column_name FROM Codes ORDER BY TimeAdded ASC"; Altered: $sql = "SELECT DATE("m", TimeAdded ) AS Date, ColumnName FROM TableName ORDER BY ...

Is this code Equivalent

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 != ...

热门标签