試圖獲得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
上午什麼我做錯了?
我沒有叫'DataWarehouse.sharedInstance'的東西 - 我想你的意思是'DataWarehouse.sharedData'?無論哪種方式,我試着你的短版本(我確實使用Swift 1.2) - 它的工作原理。而且它很有趣。我習慣使用'()'調用構造函數,但是在這裏我們訪問類的一個屬性('sharedInstance') - 並且**它實現了實例化。有點惡作劇:-)但是我知道它,它是一個靜態分配,它的工作原理 - 非常酷。謝謝! – sirab333
Woops錯字(我通常稱之爲sharedInstance)我會修改我的答案! –
正確的答案,但你也應該使init()方法私人(它默認爲公共) –