2011-09-26 123 views
0

我知道2種方法。什麼是更好的?還有什麼比兩種方式更好?共享類實例(創建和共享單例)的最佳方式是什麼?

+ (MyClass *)shared { 
    /* 
    static MyClass *sharedInstance = nil; 

    @synchronized(self) { 
     if (sharedInstance == nil) { 
      sharedInstance = [[self alloc] init]; 
     } 
    } 
    return sharedInstance; 
    */ 

    /* 
    static dispatch_once_t pred; 
    static MyClass *sharedInstance = nil; 

    dispatch_once(&pred, ^{ 
     sharedInstance = [[self alloc] init]; 
    }); 

    return sharedInstance; 
    */ 
} 

回答

2

這是另一種設置共享實例的方法。線程安全由運行時處理,代碼非常簡單。這通常是我如何設置我的單身人士。如果單例對象使用大量資源,但可能未使用,那麼dispatch_once方法運行良好。

static MyClass *sharedInstance = nil; 

+ (void) initialize 
{ 
    sharedInstance = [[MyClass alloc] init]; 
} 

+ (MyClass*)sharedInstance 
{ 
    return sharedInstance; 
} 
+0

這使得它無法配置類實例被創建方法之前。 「dispatch_once」方法是普遍接受的方法;有各種不同的方式來實現相同的事情實際上並沒有幫助。 – gnasher729

+0

我不明白你爲什麼不能配置這個類。你可以在+ load,+ initialize(在創建sharedInstance之前)配置它。在適當的時候,您甚至可以稍後在應用生命週期中更改一些sharedInstance屬性。也許我只是不明白你的意思,當然dispatch_once方法也能工作。 – aLevelOfIndirection

6

還可以在AppDelegate創建一個類實例,並在項目中的任何地方使用它。

appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; 

appappDelegate.<yourClassInstance> 
+0

我喜歡這個...... – Mrunal

+0

+1通過使用普通對象的一個​​實例來接近要求,而不是爲所有客戶實施某種類型的單個實例。 – justin

+0

不要將應用程序委託用作各種東西的通用存儲庫。這不是它的原因。 「sharedInstance」方法乾淨地將與單例相關的所有內容放到一個文件中。 – gnasher729

1

只需使用dispatch_once版本 - 它是可靠和清潔。此外,它也可以與ARC一起工作 - 與上面提出的方法不同。

1

這裏的一些細節

+ (YourClass *)sharedInstance 
{ 
    // structure used to test whether the block has completed or not 
    static dispatch_once_t p = 0; 

    // initialize sharedObject as nil (first call only) 
    __strong static id _sharedObject = nil; 

    // executes a block object once and only once for the lifetime of an application 
    dispatch_once(&p, ^{ 
     _sharedObject = [[self alloc] init]; 
    }); 

    // returns the same object each time 
    return _sharedObject; 
}