Objective-Cのシングルトンの書き方が間違ってたので正しいやり方に変えた

August 24, 2014

Objective-Cのシングルトンの書き方を変えたのでメモです。変えたというか、以前は間違ってた汗 せっかくinstancetype使っているのに返す型が固定だった。。。

+ (instancetype)sharedInstance { static id sharedInstance = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedInstance = [[self alloc] init]; }); return sharedInstance; }

以前

+ (instancetype)sharedInstance { static ResultManager *sharedInstance = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedInstance = [[ResultManager alloc] init]; }); return sharedInstance; }

最近、Objective-Cを人に教える機会があり、Singletonを書いてみたところ気づきました。最近、Objective-Cあまり書いてないからなぁ。。

参考

NYTimes/objective-c-style-guide


Profile picture

Written by morizotter who lives and works in Tokyo building useful things. You should follow them on Twitter