@ObservedObject没有更新

时间:2020-05-15 10:16:49

标签: ios swiftui combine

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

我正在使用此函数(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)
            }
        }

    }
}

1 个答案:

答案 0 :(得分:3)

应该使用与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)
            }
        }

    }
}