AechoLiu
AechoLiu

Reputation: 18378

About init question

Are there any difference between following ways to init self?

First:

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

   }
   return self;
}

Second:

- (id)init {
   if (self = [super init]) {

   }
   return self;
}

I like to use second way to init self. But I often see the first way when I create a new class by Xcode, it will generate those codes automatically. I am afraid the second way will make some errors in some condition which I don't know.

Upvotes: 0

Views: 109

Answers (4)

Asad R.
Asad R.

Reputation: 1051

Both are functionally equivalent but using assignments where conditional expressions are expected is discouraged as bad programming practice because it's usually accidental, e.g:

if (myVar = 5) {
    printf("The variable was 5\n");
}

When you actually meant to write:

if (myVar == 5) {
    ...

However the Objective-C init code is usually an exception to this because it's a well known sequence and repeated a lot, so for convenience some people may choose to write the assignment within the conditional expression.

Upvotes: 0

user557219
user557219

Reputation:

They’re equivalent and you can safely use either of them. Some people prefer not to use

if (self = [super init])

because it is a tad overloaded: it means ‘assign the return value of [super init] to self, and then evaluate self as a (boolean) condition’.

At first glance, one could misread that code, interpreting the assignment operator = as being the equality relational operator ==, i.e., ‘compare self to the value returned by [super init]’, which is not the case.

This can be particularly confusing for programmers that are new to C. Not every programming language allows assignments in expressions, that is, assignments must be in a separate instruction.

Upvotes: 1

taskinoor
taskinoor

Reputation: 46037

In C and most(if not all) languages these two are same.

First

a = b;
if (a) {}

Second

if (a = b) {}

First one is just using one more line.

However, they are not same as

if (a == b) {}

Upvotes: 2

Abizern
Abizern

Reputation: 150615

Nope, they are the same.

The second method is just missing out the first assignment of self

Another way you might come across is this:

 - (id)init  {  
    if (!(self = [super init])) {
        return nil; // Bail!
    }
    // Further initialisation   

    return self;
}

This puts the exceptional condition in the if statement, and keeps the code that you expect to run normally (the Happy Path) closer to the left margin.

Upvotes: 4

Related Questions