簡體   English   中英

為什么didSet中沒有無限循環?

[英]Why no Infinite loop in didSet?

在我的FirstViewController中,我有一個指向我的SecondViewController的按鈕,將數據傳遞給SecondViewController中的屬性。 此屬性具有屬性觀察者,在設置時創建SecondViewController的新實例。

雖然它正在按我的意願工作,但我想知道為什么它不會陷入無限循環,永遠創建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
    }
}

如果你在Swift編程語言 - 屬性中查看Apple的Swift文檔,Apple說:

注意:

如果為其自己的didSet觀察者中的屬性賦值,則分配的新值將替換剛剛設置的值。

所以如果你在didSet塊的第一行放置一個斷點,我相信它應該只被調用一次。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM