2013年8月27日 星期二

Singleton - 只要instance一次就可以當全域變數的方法


一般instance的方式:
myclass *instance = [[myclass alloc] init];

Singleton物件的方式:

myclass *instance = [myclass sharedInstance];


對於同一個物件,要在不同的view上面做共享時候

Singleton 是一個非常好用的方式

有點像是全域( global variable )變數一樣

在任何地方都可以共享他的value,

也透過這個方法作參數的傳遞.






實作方式把你要做成Singleton的物件加上

+ (MySingleton *) instance
{
    // Persistent instance.
    static MySingleton *_default = nil;
    if (_default == nil)
    {
        _default = [[MySingleton alloc] init];
    }
    return _default;
}



即可。

意即若此物件沒有被instance過, 第一次的alloc動作,

若已被instance過之後,它只會回傳指標,

這樣就可以確保在每個地方用到的"它"都是同一個物件,

就可以利用這個物件的property傳遞訊息了喔!




更詳細的做法如下:


+ (MyClass *) sharedInstance{
    // Persistent instance.
    static MySingleton *_default = nil;

    // Small optimization to avoid wasting time after the
    // singleton being initialized.
    if (_default != nil)
    {
        return _default;
    }

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0
    // Allocates once with Grand Central Dispatch (GCD) routine.
    // It's thread safe.
    static dispatch_once_t safer;
    dispatch_once(&safer, ^(void)
                  {
                      _default = [[MySingleton alloc] init];
                      // private initialization goes here.
                  });
#else
    // Allocates once using the old approach, it's slower.
    // It's thread safe.
    @synchronized([MySingleton class])
    {
        // The synchronized instruction will make sure,
        // that only one thread will access this point at a time.
        if (_default == nil)
        {
            _default = [[MySingleton alloc] init];
            // private initialization goes here.
        }
    }
#endif
    return _default;
}
@end








參考:








沒有留言:

張貼留言