Junior — Middle
Kuidas töötab oleku jälgimise mehhanism ObservedObject'iga?
sobes.tech AI
Vastus AI-lt
In SwiftUI, the state tracking mechanism using @ObservedObject is based on the ObservableObject protocol and publishing changes via @Published.
When a class is marked as ObservableObject, it can notify subscribers about changes to its properties. Properties marked as @Published automatically generate events when their values change. The SwiftUI component that uses @ObservedObject subscribes to these events and redraws itself when they occur.
Example:
class UserSettings: ObservableObject {
@Published var username: String = "Guest"
}
struct ContentView: View {
@ObservedObject var settings = UserSettings()
var body: some View {
Text("Hello, \(settings.username)!")
}
}
Here, when username in UserSettings changes, the ContentView interface automatically updates.