The Pragmatic Ball boy

iOSを中心にやってる万年球拾いの老害エンジニアメモ

戻り値はidよりもinstancetype

メソッドの戻り値の型だけにつかえるキーワードみたいなもので

A method with a related result type can be declared by using the type instancetype as its result type. instancetype is a contextual keyword that is only permitted in the result type of an Objective-C method, e.g.

@interface A
+ (instancetype)constructAnA;
@end
from http://clang.llvm.org/docs/LanguageExtensions.html#objective-c-features

使うメリットとしてはid型に比べてtype safeであることで 例えば


#import "A.h"

@implementation A
-(instancetype)funcA
{
    return self;
}
@end

Aを継承したBでAではない型を返そうとした場合に


@implementation B
-(instancetype)funcA
{
    return @[];
}
@end

このような場合とかにコンパイラがincompatible pointer castingのワーニングを吐くようになります。

なので暗黙的に返す型が決まっているような場合はidではなくinstancetypeを使ったほうがいいです。


参考