• 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

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

posted by satoko satoko on Tue 28 Jun 2011 at 11:23 with 0 comments