Are these two instancetype initialization methods equal?

70 Views Asked by At

I was wondering are these two equal:

A single parentheses inside the if statement:

- (instancetype)init {
    
    if (self = [super init]) {
        
        // ...
    }
    
    return self;
}

Double parentheses inside the if statement:

- (instancetype)init {
    
    if ((self = [super init])) {
        
        // ...
    }
    
    return self;
}
3

There are 3 best solutions below

0
On BEST ANSWER

Yes,...... as it only depends on the the expression being compared no matter how many parentheses exists (that should be even)

Parentheses help compiler understand the expressions with prioritization , if statement in objective c needs at least one () while adding more will work also but it's useless

0
On

They are the same, in that they mean the same thing and produce the same code, however the compiler will behave a little differently.

In C like languages an easy typing mistake that is visually hard to spot is to enter =, that is assignment, when ==, that is equality, is intended. This error can produce very different results and hard to spot bugs. E.g.:

if (a == b) { ... }

tests whether a and b have the same value and if so the statements in the if are executed. However:

if (a = b) { ... }

assigns the value in b to a and then executes the statements if the value of a and b (they have the same value due to the assignment) is non-zero. Clearly the two behaviours are quite different.

To help out if the compiler sees a single = in an if it will issue a warning so the programmer is alerted to the possibility of a typo. The warning will be omitted if double parentheses are used:

if ((a = b)) { ... }

which is why you'll see this pattern in code. HTH

0
On

Yes, they are equal.

self is getting the reference that it needs to store after [super init] call. Both of these do the same thing.