Should init be assigning, or testing equality, on self init?

207 Views Asked by At

I cloned from https://github.com/facebook/facebook-ios-sdk.git today, and noticed two spots in the code which have this construct:

(id) init {
    if ((self == [super init])) {
        ...
    }
}

I would expect self to be assigned here, not tested for equality:

(id) init {
    if ((self = [super init])) {
        ...
    }
}

or at the very least:

(id) init {
    self = [super init];
    if (self) {
        ...
    }
}

This is within src/FBDialog.m and sample/Hackbook/Hackbook/DataSet.m.

(Sorry if this should be in the bug tracker instead; couldn't find a way to actually submit anything there... :-/

2

There are 2 best solutions below

0
AudioBubble On BEST ANSWER

It should assign self, because [super init] may return a different object than self.

Checking for equality will often work but isn't required to work. You should always assign.

I believe that recent versions of clang even emit warnings when using == in this particular case.

2
morningstar On

The template for a new Objective-C class in XCode 3 used to give you #2 (except with fewer parentheses).

Somebody who did not understand that and thought it was a mistake changed it to #1.

I guess Apple decided it was confusing so now in XCode 4 the template gives you #3. In fact it gives a warning for #2 (maybe only without the extra parentheses).