我不想初始化一个视图控制器,直到我需要显示它的视图.所以我把它放在一个懒惰的var中: lazy var foo: NSViewController! = { let foo = NSViewController() foo.representedObject = self.representedObject return f
lazy var foo: NSViewController! = { let foo = NSViewController() foo.representedObject = self.representedObject return foo }() // ... override var representedObject: Any? { didSet { if foo != nil { foo.representedObject = representedObject } } }
self.representedObject在foo被引用之前设置,但是每当我调用foo!= nil时,它都会初始化foo:c
如果已经设置了foo,我有什么办法可以测试吗?
lazy只是一个特定的lazy-instantiation模式的便利包装器(而且只是一个中等有用的模式).如果你想要自己的模式,不要使用懒惰;只是自己建造它.private var _foo: NSViewController? = nil var foo: NSViewController { if let foo = _foo { return foo } let foo = NSViewController() foo.representedObject = self.representedObject _foo = foo return foo } // This can be private or public, as you like (or you don't technically need it) var isFooLoaded: Bool { return _foo != nil } override var representedObject: Any? { didSet { if !isFooLoaded { foo.representedObject = representedObject } } }
这是为了遵循isViewLoaded模式,它解决了相同的基本问题.