What is the preferred form of the Objective-C init method?

So far I have seen how this was done in three ways:

1

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

2:

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

3:

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

Which form is more idiomatic than Objective-C?

+4
source share
4 answers
  • The most β€œmodern” approach (used by default in Xcode 4).

     - (instancetype)init { self = [super init]; if (self) { // Initialization code here. } return self; } 
  • The default value in older versions of Xcode.

     - (instancetype)init { if (self = [super init]) { // Initialization code here. } return self; } 
  • While "legal" it is very rarely seen, and I would not recommend it.

Traditionally, in Objective-C 1.0, init methods returned an id , and from later iterations of Objective-C 2.0, it is recommended that you return instancetype instead.

+5
source

All are the same, it does not matter. I recommend using one of the first two. The latter is rarely done.

You probably won't find recommendations at this level from Apple. They state that you must set the super init return value to self. How you do this is up to you.

Initializer implementation

+2
source

all three methods are correct, we usually do this.

 - (id) init { self = [super init]; if (self != nil) { // your code here } return self; } 
-1
source

the first or second is preferred. There is no need to check if it is nil, because the if condition automatically checks this. The following is a standard way to use init.

 - (id)init { self = [super init]; if (self) { <#initializations#> } return self; } 
-1
source

All Articles