Why no Infinite loop in didSet?

懵懂的女人 提交于 2019-11-30 17:31:16

问题


In my FirstViewController I have a button directing to my SecondViewController, passing data to a property in the SecondViewController. This property has a property observer, creating a new instance of the SecondViewController when set.

While it's working as I want, I wonder why it's not getting stuck in an infinite loop, creating an instance of the SecondViewController forever. And is it good practice to do it this way?

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

回答1:


If you check Apple's documentation for Swift in The Swift Programming Language - Properties, Apple says that:

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.

So if you put a breakpoint in the first line of your didSet block, I believe it should only be called once.



来源:https://stackoverflow.com/questions/29363170/why-no-infinite-loop-in-didset

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!