首页 > 解决方案 > 领域 Swift 嵌入式对象。嵌入对象数据更改时视图不更新

问题描述

我试图让我的嵌入式对象在它们发生变化时自动更新我的 SwiftUI 代码。我的代码在以下条件下工作:

  1. 对父对象本身进行更改时。2.当我将新的嵌入对象附加到父对象时。

但是,当我更新嵌入式对象中的属性时,我的 UI 不会自动更新。

'''

    class ParentObject: Object {
         @objc dynamic public var primaryKey = ""
         public let children = List<ChildObject>()
         public override class func primaryKey() -> String? {
         "primaryKey"
    }
    }

    class ChildObject: EmbeddedObject {
    let name = "Name"
    }

    class ParentObserver: ObservableObject {
    var parentResults: Results<ParentObject>

    var parents: [parent] {
    parentResults.map(parent.init)
    }
    //The embedded objects are placed in arrays inside "parents"
    
    {
    func newParent() {
    objectWillChange.send()
    //My view automatically updates to reflect the new parent
    }

    func newChild() {
    objectWillChange.send()
    //My view automatically updates to reflect the new child
    ParentObject.children.amend('a new child')
    }

    func updateChildName() {
    objectWillChange.send()
    //My view DOES NOT automatically updates to reflect the name change of the embedded 
    //object. If I exit and reenter the view the changed name show. Why does it not update 
    //automatically like the other cases?

    ParentObject.children.first(where: { whatever id }).name = "New Name" 
    }


    }
    }

'''

标签: swiftuirealmrealm-embedded-object

解决方案


推荐阅读