2015-03-31 90 views
4

在我的FirstViewController中,我有一个按钮指向我的SecondViewController,将数据传递给SecondViewController中的一个属性。该属性具有属性观察器,在设置时创建SecondViewController的新实例。为什么在didSet中没有无限循环?

虽然它正在按照我的要求工作,但我不知道为什么它没有陷入无限循环,永远创建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 
    } 
} 
+0

直觉上,它应该是,它用来产生一个无限循环,但在最近Swift Apple的“固定”变化中。 – 2015-03-31 07:52:03

+0

**这是一个bug **。点击这里:http://stackoverflow.com/questions/42144752/inner-didset-protection-bizarrely-extends-to-the-whole-class – Fattie 2017-05-02 10:59:03

回答

1

如果您检查苹果的斯威夫特文档中The Swift Programming Language - Properties,苹果表示:

注:

我如果您为其自己的didSet观察器内的属性赋值,则您分配的新值将替换刚刚设置的值。

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

+0

谢谢,做了一些测试,它仍然有点奇怪,像在SecondViewController中的'showViewController'被调用,但没有执行。 – 2015-03-31 08:09:00

+0

是的,事实上,你的代码实例化'secondViewController'两次很奇怪,首先在'FirstViewController'中的'something'中,其次在'SecondViewController'中的'didSet'中,你确定这就是你想要的吗?您不需要实例化并显示视图控制器两次。 – Edgar 2015-03-31 08:50:49

+0

这是因为我使用'SecondViewController'来显示基于'selected'的数据。基本上,用户在'FirstViewController'中选择一些内容,并用数据(基于'selected')获取'SecondViewController'。但如果用户决定获取其他数据,则可以更改“selected”,并显示新数据。另外,因为还有一些其他计算和一个带有动态数量项目的新工具栏,我只是为了创建一个'SecondViewController'的新实例而不是重新加载表格。 – 2015-03-31 09:07:00