如何在swift 2.0(iOS)中的单例类中创建可全局访问的结构数据?

Ali*_*i M 3 singleton struct ios swift

我是iOS编程和swift的新手.我正在尝试创建一个单例类来存储我的全局数据.我的全局数据是结构和此结构的数组.我想只有一个这个类的实例,因此是一个单例类.全局数据应该可供所有ViewControllers访问和编辑.我一直在寻找,除了最后一部分,我几乎已经弄明白了.这是单例类:

    import Foundations
    class Global {

     struct Info {
      var firstname:String!
      var lastname:String!
      var status:String!

      init (firstname:String, lastname:String, status:String)
       {
        self.firstname=firstname
        self.lastname=lastname
        self.status=status
       }
    }

   var testString: String="Test" //for debugging
   var member:[Info]=[]

    class var SharedGlobal:Global
     {
      struct Static 
      {static let instance = Global()}
      return Static.instance
     }
    }
Run Code Online (Sandbox Code Playgroud)

现在我想从一些viewControllers访问这个singleton类的全局变量.当我在xcode中输入时:

    Global.SharedGlobal.
Run Code Online (Sandbox Code Playgroud)

我有两个选项,一个是数组成员,另一个是testString.结构信息不可用.但是,如果我只是输入

    Global.
Run Code Online (Sandbox Code Playgroud)

然后我看到Global.Info和Global.SharedGlobal为我的选择.

为什么我无法访问我的单例类中的结构(即Global.SharedGlobal.Info)?我错过了什么?我感谢任何反馈或帮助.非常感谢提前.

aya*_*aio 9

除非有一个非常具体的理由,否则你不需要像这样嵌套类.

让我们简化一下练习的代码:

struct Info {
    // No need for these properties to be Implicitly Unwrapped Optionals since you initialize all of them
    var firstname: String
    var lastname: String
    var status: String

    init (firstname:String, lastname:String, status:String) {
        self.firstname=firstname
        self.lastname=lastname
        self.status=status
    }
}

class Global {

    // Now Global.sharedGlobal is your singleton, no need to use nested or other classes
    static let sharedGlobal = Global()

    var testString: String="Test" //for debugging

    var member:[Info] = []

}


// Use the singleton like this
let singleton = Global.sharedGlobal

// Let's create an instance of the info struct
let infoJane = Info(firstname: "Jane", lastname: "Doe", status: "some status")

// Add the struct instance to your array in the singleton
singleton.member.append(infoJane)
Run Code Online (Sandbox Code Playgroud)

现在对我来说是有道理的.一个结构,包含一些用户的信息,我可以创建它们的任何数字实例 - 和一个单独的类,唯一的,我可以存储这些信息实例,这个单例可以在任何地方使用.

这是你想要达到的目标吗?

  • 不,这种语法结构特定于单例的原因,现在不要尝试在其他上下文中复制它.////普通类将被实例化为:`let object = MyClass()`.但是这里是在静态var中完成的,所以当我们第一次调用`let singleton = Global.sharedGlobal`时,`static let sharedGlobal = Global()`被执行,但是下次它只会被访问,而不是re -created.所以它是一个单例:只用`let singleton = Global.sharedGlobal`创建一次,每个新的`let xxx = Global.sharedGlobal`只会访问它,而不是创建新的. (2认同)