Swift - 无法在Singleton中初始化对象

时间:2016-05-20 09:24:09

标签: swift singleton init

我有Object

class MyObject: NSObject {
    // some properties

    override init() {
        super.init() // not to init other properties here
        print("MyObject init!")
    }
}

Singleton

class Singleton: NSObject {
    static let sharedInstance = Singleton()
    var obj: MyObject?

    private override init() { 
        obj = MyObject()
        print("obj init")
    }
}

只有在我发表评论obj init时,我的应用才会投放(obj = MyObject()已打印)。如果我没有对其进行评论,则应用会显示一个空白屏幕,请注意不会打印MyObject init

你能告诉我这些问题以及如何解决这个问题吗?

非常感谢。

- 更新 -

我可以在obj或任何其他ViewController的didFinishLaunchingWithOption中初始化viewDidLoad

private let singleton = Singleton.sharedInstance

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

        // FIXME: - This should be initialized in Singleton
        singleton.obj = MyObject()

        return true
    }

1 个答案:

答案 0 :(得分:0)

这是创建Swift Singleton的方法:

class Singleton: NSObject {
    private static let sharedInstance = Singleton()
    private var _obj: MyObject?
    public var obj : MyObject {
       get {
       if _obj == nil {
         _obj = MyObject()
       }
       return obj
    }
    private override init() { 
      super.init()
      //Do some stuff here      
      print("obj init")
    }
}

现在您只需使用Singleton.sharedInstance.obj

但更好的实施方式是:

class MyObject: NSObject {
    private var _obj: MyObject?
    public var sharedInstance : MyObject {
       get {
       if _obj == nil {
         _obj = MyObject()
       }
       return obj
    }
    private override init() { 
      super.init()
      //Do some stuff here      
      print("obj init")
    }
}

这允许您使用:MyObject.sharedInstance,它优于Singleton.sharedInstance.obj