Sami Almalki
Sami Almalki

Reputation: 628

SwiftUI ObservedObject is re-initiated everytime

I have a simple class to store some data in my SwiftUI app:

final class UserData: ObservableObject  {
    @Published var id = 1
    @Published var name = "Name"
    @Published var description = "Initial text"
}

I also defined it as EnvironmentObject in the main app struct:

ContentView(document: file.$document)
    .environmentObject(UserData())

In my Content View, I embedded a UIKit Text View:

EditorTextView(document: $document.text)

Where EditorTextView is a UITextView that is applied through UIViewRepresentable.

Now, what I'm trying to do is to update UserData within EditorTextView, like, storing some user input into UserData.description. So I defined the class inside my Coordinator as follows (the code is just for example):

class Coordinator: NSObject, UITextViewDelegate {
    @ObservedObject var userData = UserData()
    ...
    // Somewhere in the code, I update UserData when user taps Enter:
    func textViewDidChange(_ textView: UITextView) {
        if (textView.text.last == "\n") {
            userData.description = "My New Text"
        }
    }

My problem is:

Although it is updated with "My New Text" (as debugger shows), the value of userData.description is re-initiated again with the value "Initial text". It's like if UserData class is created everytime.

I tried to use @StateObject instead of @ObservedObject, but it doesn't make a difference.

Upvotes: 1

Views: 881

Answers (1)

"It's like if UserData class is created everytime."

It is created everytime, right here:

class Coordinator: NSObject, UITextViewDelegate {
    @ObservedObject var userData = UserData()  // <--- here

Try this instead, and pass the UserData in from outside:

class Coordinator: NSObject, UITextViewDelegate {
    @ObservedObject var userData: UserData

Typically you would also do this in your main app struct:

@StateObject var userData = UserData()
...
ContentView(document: file.$document).environmentObject(userData)

Upvotes: 4

Related Questions