0

我将 json 数据从 iPhone 解码到手表并将其存储到声明为 @ObservableObject 的对象(自定义类:PeopleObj)中。但是,包含此对象的内容视图没有获取数据

这是数据模型:

struct Person: Codable {
    var pid : UUID
    var dept: String
    var name: String

    init(pid: UUID, dept: String, name: String){
        self.pid = pid
        self.dept = dept
        self.name = name
    }
}
    
class PeopleObj: ObservableObject, Identifiable , Codable{
    @Published var people: [Person] = []
        
    // get codable
    init() { }
    
    enum CodingKeys: CodingKey {
        case people
    }
    
    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(people, forKey: .people)
        
    }
    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        people = try container.decode(Array.self, forKey: .people)
    }
}

以下是 WatchOS 的解码部分,这里我将 json 数据作为对请求的回复,并将其解码为 peopleObj:

let jsonEncoder = JSONEncoder()
do {
    let jsonDataRequest = try jsonEncoder.encode(request)
    print("send request")
    self.session?.sendMessageData(jsonDataRequest, replyHandler: { response in
        print(">>>>>>>>>>>>>>>>> DATA-Reply vom iPhone received: \(response)")
        DispatchQueue.main.async {
            let jsonDecoder = JSONDecoder()
            do {
                self.peopleObj = try jsonDecoder.decode(PeopleObj.self, from: response)
                for person in self.peopleObj.people {
                    print("received person: \(person.name), dept \(person.dept)")
                    // here it prints correctly
                }
                                
            } // End do decode
            catch { print("decode catch!!!!!!!")  }
        } // Dispatch main
    },
    errorHandler: { error in
        print("Error sending message: %@", error)
    }) // sendMessageData
} // End do decode
catch { print("encode catch!!!!!!!")  }

这是contenview,观察对象:

struct ContentView: View {
        
    @ObservedObject var peopleObj: PeopleObj
        
    var body: some View {
     
        VStack {
            List(peopleObj.people, id: \.pid) { person in
                HStack {
                    Text("name: \(person.name)")
                    Spacer()
                    Text("dept: \(person.dept)")
                }
            }
        }
    }
}

我尝试将 json 解码为一个结构,然后手动将值添加到 peopleObj - 这有效,但对我来说似乎不是正确的过程!我无法解释为什么,猜想它与价值与引用有关。

任何帮助和/或想法都非常受欢迎!!!!!!!

编辑: peopleObj 在 HostingController 中定义:

    class HostingController: WKHostingController<ContentView> , WCSessionDelegate{
   
   @ObservedObject var peopleObj:PeopleObj = PeopleObj()

从 HostingController 调用 ContentView

 override var body: ContentView {
     return ContentView(peopleObj: peopleObj)
}
4

0 回答 0