swift – 为什么didSet中没有无限循环?

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

虽然它正在按我的意愿工作,但我想知道为什么它不会陷入无限循环,永远创建SecondViewController的实例.这样做是不错的做法?

FirstViewController:

class FirstViewController: UIViewController {
    @IBAction func something(sender: UIButton) {
        let destination = storyboard?.instantiateViewControllerWithIdentifier("secondViewController") as SecondViewController
        destination.selected = 1
        showViewController(destination, sender: self)
    }
}

SecondViewController:

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

最佳答案 如果你在
The Swift Programming Language – Properties查看Apple的Swift文档,Apple会说:

Note:

If you assign a value to a property within its own didSet observer, the new value that you assign will replace the one that was just set.

所以如果你在didSet块的第一行放置一个断点,我相信它应该只被调用一次.

点赞