Swift 单例不工作

Swift Singleton not Working

正在尝试让一个单身人士 class 进入 Swift。我没有收到任何错误,但它也无法正常工作。

代码如下:

// 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 

}

接下来,我创建了两个 classes,它们可以访问 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)")
    }

}

这是第二个 class - 它与 A 类基本相同:

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.sharedData,而不是 DataWarehouse(),当您是 'constructing' 另一个数据仓库对象时classes.

目前您从未真正访问过 sharedInstance。

如果您使用 Swift 1.2 并且更喜欢,您可以使用一些带有 class 常量(延迟初始化)的更清晰的文本:

class Singleton {

    static let sharedInstance = Singleton()

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

}

如上,但将 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