Singletonを使う場面はよくあるんですが、iOS4以降はGrand Central Dispatchがあるのでそれのdispatch_onceを使う必要があるみたいで、メモ。
GCD 前:
rails>>
(MyController*)singleton {
static MyController *controller = nil;if(!controller) {
controller = [[MyController] alloc] init];
}
return controller;
}
<<--
GCD 後:
rails>>
(MyController*)singleton {
static dispatch_once_t pred = 0;
static MyController *controller = nil;dispatch_once(&pred, ^{
controller = [[MyController alloc] init];
});
return controller;
}
<<--
Cocoa Fundamentals GuideのClass Factory Methods項の下のほーーーうにあるCreating a Singleton Instanceの説明もとても参考になります。これは読むべし:
Cocoa Fundamentals Guide
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaObjects/CocoaObjects.html#//apple_ref/doc/uid/TP40002974-CH4-SW32
また、Apple Developer Forumsのこの質問もとても勉強になります:
Apple Developer Forums
https://devforums.apple.com/message/455002#455002
下記も参考
Singletons: You're doing them wrong
http://cocoasamurai.blogspot.com/2011/04/singletons-your-doing-them-wrong.html