中读取和写入相同的

中读取和写入相同的

本文介绍了我们如何在 SwiftUI 中读取和写入相同的 ObservableObject?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个 ObservableObject 类,然后我使用它在所有应用程序中读取和写入值.当我在 StateObject 和 ObservedObject 中使用我的 ObservableObject 时,它们不是相同的数据,但它们在内存中创建了不同的变量,我们如何制作 StateObjectObservedObject 处理相同的数据?

I am making a ObservableObject class and then I am using it for reading and writing value in all app. when I am using my ObservableObject in my StateObject and ObservedObject, they are not the same data, but they are making a different variable in memory, how we can make StateObject and ObservedObject working on a same data?

例如,我的 ObservableObject 类有一个名为 stringOfText 的变量,默认情况下它有 No Data! 然后我创建一个 StateObject 变量并开始读取 的默认值stringOfText,然后我更改 stringOfText 的默认值,但它不会在我的 ObservedObject 中显示更新!我做错了什么?

For example my ObservableObject class has a variable called stringOfText, which as default has No Data! then I make a StateObject variable and start reading default value of stringOfText, then I change the default value of stringOfText and it does not show the update in my ObservedObject! what I am doing wrong?

class TextModel: ObservableObject {
    @Published var stringOfText: String = "No Data!"
}

struct ContentView: View {
    @ObservedObject var readStringOfTextView = TextModel()

    var body: some View {
        TextView()

        Text(readStringOfTextView.stringOfText)
            .foregroundColor(Color.black)
    }
}

struct TextView: View {
    @StateObject var textModel = TextModel()

    var body: some View {
        Text(textModel.stringOfText)
            .padding()
            .foregroundColor(Color.red)

        Button(action: {
            textModel.stringOfText = "Hello, world!"

        }) {
            Text("update string of Text")
                .padding()
        }
    }
}

推荐答案

您可以通过共享实例来实现,例如:

You can make it via shared instance, in example:

class TextModel: ObservableObject {
    static let shared = TextModel()     // << here !!

    @Published var stringOfText: String = "No Data!"
}

struct ContentView: View {
    @ObservedObject var readStringOfTextView = TextModel.shared  // << here !!

// ... other code
}

struct TextView: View {
    @StateObject var textModel = TextModel.shared // << here !!

// ... other code
}

这篇关于我们如何在 SwiftUI 中读取和写入相同的 ObservableObject?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-04 22:07