为什么didSet中没有无限循环? [英] Why no Infinite loop in didSet?

查看:106
本文介绍了为什么didSet中没有无限循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的FirstViewController中,我有一个指向我的SecondViewController的按钮,将数据传递到SecondViewController中的一个属性.该属性具有属性观察器,设置后会创建SecondViewController的新实例.

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.

尽管它可以按我的方式工作,但我想知道为什么它不会陷入无限循环中,从而永远创建SecondViewController的实例.这样做是一种好习惯吗?

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:

FirstViewController:

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

SecondViewController:

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

推荐答案

如果您在

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

注意:

如果您在其自己的didSet观察器中为属性分配值,则您分配的新值将替换刚刚设置的值.

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块的第一行中放置一个断点,则我相信它只能被调用一次.

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

这篇关于为什么didSet中没有无限循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆