[iPhone SDK] iPhone SDK で Singleton

自分でもよく忘れるので、備忘録的に書いてみる。

iPhone SDKで開発をしていて、時々シングルトンオブジェクトが欲しくなる。
その場合には、Derek Neely で紹介されているとおり、2つのやり方があると思われる。

  1. AppDelegateに変数を持たせて、使う側は [UIApplication sharedApplication] でアクセスする
  2. シングルトンクラスを作る

1. のAppDelegate 方式は本などでもよく使われていると思う。実際、UIApplication の sharedApplication はシングルトンオブジェクトを取得するものだと思うのでやり方としては間違っていないとは思う。(上記の Derek Neely ではこの方式はおすすめされていないが)

シングルトンクラスを作る場合、マイコミジャーナルのダイナミックObjective-C が参考になる。

他にも自分がシングルトンクラスを作ったときに参考にしたページがあったと思ったが忘れてしまった… 思い出したら追記しよう。

2010/09/21 追記:

結局ページは見つからなかったが、Erica Sadun の The iPhone Developer’s Cookbook 2nd EditionのP119 “Crafting Singletons”にのっていた。

Objective-C でシングルトンパターン | Sun Limited Mt.にも載っていた。

@implementation History  
  
static History* sharedHistory = nil;  
  
+ (History*)sharedInstance {  
        if (!sharedHistory) {  
            sharedHistory = [[self alloc] init];  
        }  
    }  
    return sharedHistory;  
}  
  
+ (id)allocWithZone:(NSZone *)zone {  
    @synchronized(self) {  
        if (sharedHistory == nil) {  
            sharedHistory = [super allocWithZone:zone];  
            return sharedHistory;  
        }  
    }  
    return nil;  
}  


追記 2011/09/05

よく見ると、上記全てが参照しているのはAppleのページらしい。
Cocoa Fundamentals Guide: シングルトンインスタンスの作成

追記 2011/10/16

上記のCocoa Fundamentals Guide: シングルトンインスタンスの作成で、下記がなぜ [[self alloc]init] で良いのか理解できていなかったが、Singleton ADC example – dealloc and assignment | Cocoabuilder を読んで思い出した。

+ (MyGizmoClass*)sharedManager
{
    @synchronized(self) {
        if (sharedGizmoManager == nil) {
            [[self alloc] init]; // ここでは代入していない ← init しているのにどこにも代入してない?
        }
    }
    return sharedGizmoManager;
}

+ (id)allocWithZone:(NSZone *)zone {
{
    @synchronized(self) {
        if (sharedGizmoManager == nil) {
            sharedGizmoManager = [super allocWithZone:zone];
            return sharedGizmoManager;  // 最初の割り当てで代入し、返す
        }
    }
    return nil; // 以降の割り当てではnilを返すようにする
}

alloc は +(id)allocWithZone:(NSZone*)zone の 引数 nil 版なので alloc を呼ぶと allocWithZone:nil が呼ばれるので、[[self alloc]init] するだけで良いのだった。
このあたりは、詳解 Objective-C 2.0 改訂版 でくわしく説明されている。
ただ、このコードは正直ちょっとやり過ぎな気もしていて、自分だけで使うSingletonのコードであればここまでやらなくても良いと思われる。
iphone – Apple Singleton example query? – Stack Overflow
あたりでもそう書かれていた。
また、初期化コードはふつうにinitの中に書くのでよいとのこと。
iphone – Cocoa – Singleton object: Where to initialize member variables? – Stack Overflow

マクロでSingleton を実現する例。AppDelegate 方式は悪だとも書いてあった。
Cocoa with Love: Singletons, AppDelegates and top-level data.

The iPhone Developer’s Cookbook: Building Applications with the iPhone 3.0 SDK (2nd Edition) (Developer’s Library)
The iPhone Developer's Cookbook: Building Applications with the iPhone 3.0 SDK (2nd Edition) (Developer's Library) Erica Sadun

Addison-Wesley Professional 2009-12-28
売り上げランキング : 28518

Amazonで詳しく見る by G-Tools

詳解 Objective-C 2.0 改訂版
詳解 Objective-C 2.0 改訂版 荻原 剛志

ソフトバンククリエイティブ 2010-12-17
売り上げランキング : 2192

Amazonで詳しく見る by G-Tools

返信を残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

This site uses Akismet to reduce spam. Learn how your comment data is processed.