当我使用房产时,我遇到过很奇怪的情况lazy
关键词。我知道这个关键字表示属性的初始化将被推迟到实际使用变量为止。但是,它并没有像我预期的那样工作。它运行两次。
class TestLazyViewController: UIViewController {
var name: String = "" {
didSet {
NSLog("name self = \(self)")
testLabel.text = name
}
}
lazy var testLabel: UILabel = {
NSLog("testLabel self = \(self)")
let label = UILabel()
label.text = "hello"
self.view.addSubview(label)
return label
}()
override func viewDidLoad() {
super.viewDidLoad()
testLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
NSLayoutConstraint.activateConstraints([NSLayoutConstraint(item: testLabel, attribute: .CenterX, relatedBy: .Equal, toItem: self.view, attribute: .CenterX, multiplier: 1.0, constant: 0.0)])
NSLayoutConstraint.activateConstraints([NSLayoutConstraint(item: testLabel, attribute: .CenterY, relatedBy: .Equal, toItem: self.view, attribute: .CenterY, multiplier: 1.0, constant: 0.0)])
}
@IBAction func testButton(sender: AnyObject) {
testLabel.text = "world"
}
}
我写了一个视图控制器进行测试。该视图控制器由另一个视图控制器呈现。然后,name
属性设置在prepareForSegue
呈现视图控制器的。
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let vc = segue.destinationViewController as! TestLazyViewController
println("vc = \(vc)")
vc.name = "hello"
}
运行测试时,我得到以下结果。
vc = <testLazy.TestLazyViewController: 0x7fb3d1d16ec0>
2015-05-25 00:26:15.673 testLazy[95577:22267122] name self = <testLazy.TestLazyViewController: 0x7fb3d1d16ec0>
2015-05-25 00:26:15.673 testLazy[95577:22267122] testLabel self = <testLazy.TestLazyViewController: 0x7fb3d1d16ec0>
2015-05-25 00:26:15.674 testLazy[95577:22267122] testLabel self = <testLazy.TestLazyViewController: 0x7fb3d1d16ec0>
如您所见,初始化代码执行了两次。我不知道这是一个错误还是误用的结果。有谁可以让我知道出了什么问题吗?
我猜参考testLabel
with self.view
初始化代码中不正确。
UPDATE:
我仍然不明白为什么延迟初始化运行两次。这真的是 Swift 的 bug 吗?
最终更新:
@matt 对这个被初始化两次的问题做了很好的解释。我能够获得宝贵的知识lazy
关键字有效。谢谢马特。