4

在我的 FirstViewController 中,我有一个指向我的 SecondViewController 的按钮,将数据传递给 SecondViewController 中的一个属性。该属性有一个属性观察者,在设置时会创建一个 SecondViewController 的新实例。

虽然它按我的意愿工作,但我想知道为什么它没有陷入无限循环,永远创建 SecondViewController 的实例。这样做是个好习惯吗?

第一视图控制器:

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
    }
}
4

1 回答 1

2

如果您在The Swift Programming Language - Properties中查看 Apple 的 Swift 文档,Apple 会说:

笔记:

如果您在其自己的 didSet 观察者中为属性分配一个值,您分配的新值将替换刚刚设置的值。

因此,如果您在didSet块的第一行放置一个断点,我相信它应该只被调用一次。

于 2015-03-31T07:53:49.603 回答