在我的 FirstViewController 中,我有一个指向 SecondViewController 的按钮,将数据传递到 SecondViewController 中的属性。该属性有一个属性观察者,在设置时创建 SecondViewController 的新实例。
虽然它按我想要的方式工作,但我想知道为什么它没有陷入无限循环,永远创建第二个 ViewController 的实例。这样做是好的做法吗?
第一个视图控制器:
class FirstViewController: UIViewController {
@IBAction func something(sender: UIButton) {
let destination = storyboard?.instantiateViewControllerWithIdentifier("secondViewController") as SecondViewController
destination.selected = 1
showViewController(destination, sender: self)
}
}
第二个视图控制器:
class SecondViewController: UIViewController {
var selected: Int = 0 {
didSet {
let destination = storyboard?.instantiateViewControllerWithIdentifier("secondViewController") as SecondViewController
destination.selected = selected
showViewController(destination, sender: self)
}
}
@IBAction func something(sender: UIButton) {
selected = 2
}
}
如果您查看 Apple 的 Swift 文档Swift 编程语言 - 属性,苹果表示:
Note:
如果您向其自己的 didSet 观察器内的属性分配一个值,则您分配的新值将替换刚刚设置的值。
因此,如果您在第一行放置一个断点didSet
块,我相信它应该只被调用一次。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)