Reputation: 3052
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
}
}
Upvotes: 4
Views: 2429
Reputation: 2540
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.
Upvotes: 2