开发者

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.


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.


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) {}


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜