尝试在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。
我做错了什么?
答案 0 :(得分:3)
如果你使用这种单身方法,要实际访问单身,你需要使用DataWarehouse.sharedData
,而不是DataWarehouse()
,当你构建'其他类中的datawarehouse对象。
目前您从未真正访问过sharedInstance。
如果您使用的是Swift 1.2并且更喜欢,您可以使用一些带有类常量的清洁文本(延迟初始化):
class Singleton {
static let sharedInstance = Singleton()
init() {
println("Hello");
}
}
答案 1 :(得分: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