2015-06-22 73 views
0

試圖獲得Swift中的單例類。我沒有得到任何錯誤,但它也只是不能正常工作。Swift Singleton不能正常工作

下面的代碼:

// The Singleton class: 
class DataWarehouse { 
    class var sharedData:DataWarehouse { 
     struct Static { 
      static var onceToken : dispatch_once_t = 0 
      static var instance : DataWarehouse? = nil 
     } 
     dispatch_once(&Static.onceToken) { 
      Static.instance = DataWarehouse() 
     } 
     return Static.instance! 
    } 

    // Here's a variable that I want to pass around to other classes: 
    var x = 10 

} 

接下來,我創建了一個可以訪問的價值x並使用它,改變它的價值兩班,等:

class ClassA { 

    var theData = DataWarehouse() 

    func changeX() { 
     // First, log out the current value of X: 
     println("ClassA ==> x is currently: \(theData.x)") 

     // Next, change it: 
     theData.x = -50 
     println("ClassA ==> x was just set to: \(theData.x)") 
    } 

} 

這裏的第二類 - 其基本上與ClassA相同:

class ClassB { 

    var theData = DataWarehouse() 

    func changeX() { 
     // First, log out the current value of X: 
     println("ClassB ==> x is currently: \(theData.x)") 

     // Next, change it: 
     theData.x = -88 
     println("ClassB ==> x was just set to: \(theData.x)") 
    } 

} 

最後,在main.swift我把整個事情:

let objectA = ClassA() 
objectA.changeX() 

let objectB = ClassB() 
objectB.changeX() 

我得到的輸出是:

ClassA ==> x is currently: 10 
ClassA ==> just set x to: -50 
ClassB ==> x is currently: 10 
ClassB ==> just set x to: -88 

所以x值並不能真正得到更新,它總是10

上午什麼我做錯了?

回答

3

如果您使用這種單例方法,當您在其他類中構建datawarehouse對象時,要實際訪問單例,您需要使用DataWarehouse.sharedData而不是DataWarehouse()

此刻你永遠不會實際訪問sharedInstance。

如果您使用的雨燕1.2和喜歡,你可以使用與類常量的清潔文本(懶惰初始化):

class Singleton { 

    static let sharedInstance = Singleton() 

    init() { 
     println("Hello"); 
    } 

} 
+0

我沒有叫'DataWarehouse.sharedInstance'的東西 - 我想你的意思是'DataWarehouse.sharedData'?無論哪種方式,我試着你的短版本(我確實使用Swift 1.2) - 它的工作原理。而且它很有趣。我習慣使用'()'調用構造函數,但是在這裏我們訪問類的一個屬性('sharedInstance') - 並且**它實現了實例化。有點惡作劇:-)但是我知道它,它是一個靜態分配,它的工作原理 - 非常酷。謝謝! – sirab333

+0

Woops錯字(我通常稱之爲sharedInstance)我會修改我的答案! –

+0

正確的答案,但你也應該使init()方法私人(它默認爲公共) –

0

如上,但要在init私人,使實例被迫使用sharedInstance

class Singleton { 
    static let sharedInstance = Singleton() 
    private init() { 
     // Only methods within the class can access here 
    } 
} 

然後

let single = Singleton() // Is not allowed by the compiler 

你必須使用

let single = Singleton.sharedInstance