gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 19:35:15 27 4
gpt4 key购买 nike

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

虽然它按我想要的方式工作,但我想知道为什么它不会陷入无限循环,永远创建 SecondViewController 的实例。这样做是好的做法吗?

第一 View Controller :

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

第二 View Controller :

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 block 的第一行放置一个断点,我相信它应该只被调用一次。

关于swift - 为什么 didSet 中没有无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29363170/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com