快速访问单例对象

就职

这是我第一次实现单例以快速共享对象实例。一切似乎都工作正常,除了我尝试将元素添加到驻留在我的单例对象中的数组(从另一个类访问)时。实际上,它根本没有将任何对象附加到数组。我在想它是追加到数组上,但不是我想要的类的同一实例(因为我只想要一个且只有一个实例)。但是,如果我从类的init()将元素追加到数组上,一切都会正常进行。这是一些代码(我简化了所有类以使事情变得更明显):

文件1:

class Brew: NSObject {
  var method = Method()

  //Singleton variable
  private static var currentBrew: Brew?

  //Method to get the current (and only) brew object
  static func getCurrentBrew() -> Brew {
    if currentBrew == nil {
        currentBrew = Brew()
    }
    return currentBrew!
  }

}

struct Method {
  var chemex = Device()

init() {
  //If I append here - everything works fine
  //chemex.instructions.append = (Instruction(title: "Prepare", direction: "Prewet & Heat", time: 3, water: 0))
}

}

struct Device {
  var instructions = [Instruction]() 

init() {
    instructions.append(Instruction(title: "None", direction: "None", time: 1, water: 0, index: 0)) 
}

文件2 :(我想附加到指令数组的位置)

let brew = Brew.getCurrentBrew() //How i'm accessing the object

//I'm calling this method from viewDidLoad to set up the array
func setupBrewDevices() {
  //This is the line that does not actually append to the singleton instance
  brew.method.chemex.instructions.append(Instruction(title: "Extraction", direction: "Match water.", time: 8 , water: 25))

只是附带说明,我还尝试了一种方法,该方法会将指令添加到位于同一类内部的数组中,但结果相同。希望这很清楚-感谢您的帮助!

谢谢科尔

马克·哈德佩(Marc Khadpe)

在Swift中有一种更好的方法来创建单例实例。

class Brew: NSObject {
    static let currentBrew = Brew()

    var method = Method()
}

这是线程安全的,并避免使用可选的。

就是说,当我尝试您的代码时,指令数组以两个元素结尾,就像我期望的那样(“无”)和(“提取”)。问题可能出在代码的其他地方。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章