gpt4 book ai didi

ios - @ObservedObject 未更新

转载 作者:行者123 更新时间:2023-12-01 18:34:46 24 4
gpt4 key购买 nike

我正在尝试使用简单的 Observable 模式更新 View ,但由于某种原因它没有发生。发布者得到更新,但订阅者没有。我已经简化为下面的代码。当您单击“添加”按钮时, View 和变量都不会更新。

我正在使用此功能(NetworkManager.shared.saveNew()),因为我在收到 CloudKit 通知后更新。如果您知道解决方法,我很高兴知道!

import SwiftUI
import Combine

public class NetworkManager: ObservableObject {
static let shared = NetworkManager()

@Published var list = [DataSource]()

init() {
self.list = [DataSource(id: "Hello", action: [1], link: "http://hello.com", year: 2020)]
}

func saveNew(item: DataSource) {
self.list.append(item)

}
}

struct DataSource: Identifiable, Codable {

var id: String
var action: [Int]
var link: String
var year: Int

init(id: String, action: [Int], link: String, year: Int) {
self.id = id
self.action = action
self.link = link
self.year = year
}
}


struct ContentView: View {

@ObservedObject var list = NetworkManager()

var body: some View {
VStack {
Button("Add") {
NetworkManager.shared.saveNew(item: DataSource(id: "GoodBye", action: [1], link: "http://goodbye", year: 2030))

}
List(list.list, id:\.id) { item in
Text(item.id)
}
}

}
}

最佳答案

应该使用 NetworkManager 的相同实例,所以这里是固定的变体(最好将管理器命名为 manager 而不是 list )

struct ContentView: View {

@ObservedObject var manager = NetworkManager.shared // << fix !!

var body: some View {
VStack {
Button("Add") {
self.manager.saveNew(item: DataSource(id: "GoodBye", action: [1], link: "http://goodbye", year: 2030))

}
List(manager.list, id:\.id) { item in
Text(item.id)
}
}

}
}

关于ios - @ObservedObject 未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61816898/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com