Should instancetype be used on alloc/new/init methods?
Asked Answered
P

1

13

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.

Pandanus answered 30/5, 2013 at 21:18 Comment(0)
V
19

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.

Verbatim answered 30/5, 2013 at 21:25 Comment(2)
The default is "id", not instancetype. Returning instancetype gives you more type checking. There's no difference if your code is correct, but the compiler might miss mistakes if you return id.Passkey
@Passkey See the instancetype documentation in llvm (clang.llvm.org/docs/LanguageExtensions.html). instancetype is automatically inferred for certain methods and, as a result, instancetype is the default in those cases.Verbatim

© 2022 - 2024 — McMap. All rights reserved.