簡體   English   中英

觀察數組中任何成員的任何屬性的變化

[英]Observe changes in any property of any member of an array

我有一個存儲一個類的對象的數組:

class Apple {

    var color = "Red"

}

let myApple = Apple()

var apples = [Apple]()

apples.append(myApple)

// Func should be called here
myApple.color = "Blue"

let otherApple = Apple()

// Func should not be called here, 
// because otherApple is not a member of apples array
otherApple.color = "Green"

我想在“ apples”數組的任何成員的任何屬性已更改的情況下運行一個函數。 調用此函數時,我需要傳遞屬性更改為參數的數組項。

我曾想過在color屬性上使用didSet ,但是在這種情況下,otherApple的屬性也被更改時就會調用該函數。 這不是我想要的。 我只想在數組成員的屬性已更改時運行該函數。 如果它不是成員,則該函數不應運行。

使用didSetdidSet運行該函數,並在函數的開頭檢查成員資格可能是一個主意,但我覺得這不是一個好方法。

如何使用Swift正確實現這一目標?

編輯:Apple 在Swift中使用鍵值觀察的指南

您需要將observer添加到要在apples array添加的所有Apple對象中。

首先在類級別創建一個名為[NSKeyValueObservation]類型的observers的屬性,即

var observers = [NSKeyValueObservation]()

現在,創建一個將新的Apple實例追加到apples array並為其添加observer方法,

func addNewApple(_ apple: Apple) {
    observers.append(apple.observe(\.color, options: [.new], changeHandler: { (apple, changes) in
        if let newValue = changes.newValue {
            print(newValue)
        }
    }))
    apples.append(apple)
}

要觀察對象的屬性,必須將其標記為@objc dynamic 因此, Apple定義就像

class Apple: NSObject {
    @objc dynamic var color = "Red"
}

現在,您可以按以下說明使用它,

let myApple = Apple()
self.addNewApple(myApple)
myApple.color = "Blue"

結合所有零碎的部分,整個代碼可以這樣寫:

 class VC: UIViewController { var apples = [Apple]() var observers = [NSKeyValueObservation]() override func viewDidLoad() { super.viewDidLoad() let myApple = Apple() self.addNewApple(myApple) myApple.color = "Blue" let otherApple = Apple() otherApple.color = "Green" } func addNewApple(_ apple: Apple) { observers.append(apple.observe(\\.color, options: [.new], changeHandler: { (apple, changes) in if let newValue = changes.newValue { print(newValue) } })) apples.append(apple) } } 

暫無
暫無

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

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