Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should instancetype be used on alloc/new/init methods?

According to the clang documentation, a method that returns id is implicitly known to return instancetype when it is a class method beginning with new or alloc, or an instance method beginning with retain, autorelease, init, or self.

For the sake of consistency, should these methods also be written to explicitly return instancetype in new code?

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

Is there any documentation on why or why not, or any reasoning? It seems that in this case it's interpreted exactly the same to the compiler.

like image 322
wjl Avatar asked May 30 '13 21:05

wjl


1 Answers

It isn't actually necessary because the compiler automatically promotes such methods to returning instancetype, effectively (as you stated).

This automatic inference is documented in the llvm documentation.

Personally? I always declare them as instancetype explicitly because it exactly describes the contract and it makes for easier refactoring later.

like image 84
bbum Avatar answered Oct 24 '22 10:10

bbum