簡體   English   中英

未在 realm 屬性上調用 WillSet/DidSet

[英]WillSet/DidSet not being invoked on realm property

我有一個問題,因為willSetdidSet沒有被動態 realm object 調用。

代碼示例:

try! realm.write {
    sut = Backup()
    realm.add(sut) // here willSet and didSet are invoked with nil object
}

XCTAssertFalse(sut.didEditPatient) // ok
try! realm.write {
    print("CHECKING: will add the patient")
    let patient = Patient()
    realm.add(patient)
    sut.patient = patient // nothing gets printed here!
    print("CHECKING: added the patient")
}

XCTAssertTrue(sut.didEditPatient) // fails
XCTAssertNotNil(sut.patient) // ok

其中備份 class 是這樣定義的:

final class Backup: Object {
    @objc dynamic var patient: Patient? {
        willSet {
            print("CHECKING: willSet: \(String(describing: newValue))")
            if newValue != patient {
                didEditPatient = true
            }
        }
        didSet { print("CHECKING: didSet: \(String(describing: patient))") }
    }
    @objc dynamic var didEditPatient: Bool = false

控制台中的 Output 為:

  • 檢查:willSet:無
  • 檢查:didSet:無
  • CHECKING:將添加患者
  • CHECKING:添加了患者

雖然我更希望在will add the patientadded the patient之間我應該得到willSetdidSet與患者 object。 顯然,耐心不是零。

realm repo 中描述了一個關於此的問題:


我建議使用沒有邏輯的私有持久屬性,以及具有 willSet/didSet 功能的非持久計算屬性:

class Model : RLMObject {
    private dynamic var backingProp = 0

    var prop : Int {
        get {
            return backingProp
        }
        set(newValue) {
            // do willSet stuff
            backingProp = newValue
            // do didSet stuff
        }
    }

    override class func ignoredProperties() -> [AnyObject]! {
        return ["prop"]
    }
}

這有點冗長,但為 realm 中的對象和獨立對象提供了相同的行為。


來源: https://github.com/realm/realm-cocoa/issues/870#issuecomment-54543539

這很容易解決。 只需在寫入 Realm 之前更新對象屬性。 willSet 和 didSet 是 Swift 構造,而不是 Objc。

let p = Patient()
try! realm.write {
    print("CHECKING: will add the patient")
    sut.patient = p // moved before add to realm.
    realm.add(p)
    print("CHECKING: added the patient")
}

將打印

CHECKING: will add the patient
willSet
didSet
CHECKING: added the patient

這是你想要的順序。

暫無
暫無

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

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