ios - 快速访问单例对象

标签 ios swift oop singleton

这是我第一次在 swift 中实现单例来共享对象的实例。一切似乎都工作得很好,除了当我尝试将元素添加到位于我的单例对象中的数组(从另一个类访问)中时除外。它确实根本不向数组添加任何对象。我认为它附加到一个数组上,但不是我希望的类的同一个实例(因为我只想要一个且只有一个实例)。但是,如果我从类的 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))

顺便说一句,我还尝试创建一种方法,将指令附加到位于同一类内部的数组上,但结果相同。希望这足够清楚 - 我感谢任何帮助!

谢谢, 科尔

最佳答案

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

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

    var method = Method()
}

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

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

关于ios - 快速访问单例对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34101899/

相关文章:

oop - 如何在抽象派生类型中设计 PRIVATE OVERRIDABLE 过程?

java - 查找映射值并调用匹配的实现

javascript - 如何访问类范围之外的变量

ios - UITouch坐标和SKSpriteNode坐标不同

iphone - 通过调用CFRelease与使用CGColorSpaceRelease释放CGColorSpaceRef的区别?

ios - 在 swift 中以不同方式处理 printf

swift - iOS 8 Beta Today 扩展小部件未显示在 Swift 应用程序中?

保护两者的 Swift 惯用方法不是零

ios - 在应用程序之间共享信息

iOS 播放 - "Playing on your TV"