I wanted to get my apple watch data on my iPhone in a different view using @StateObject. This worked fine, but recently I wanted to clean up my code with the MVVM (Modelview-ViewModel). So I wrote an extension where all the backend code runs in an extra file.
Now I observed that moving all my code in an extension, comes with some problems. One of them is that I don’t get any data from my WatchManager-Class in my extension. The value never changes!
I know the @Published should update its value if I write new changes to it. The @StateObject is than creating an instance of the watchmanager and watches for changes, this is true for my RecordView, but for any reason deltaDistance2 won’t change if I set a new value the extension.
I don’t know what to do or how to solve this challenge. Can anybody help? Here is my Code:
import SwiftUI
struct RecordView: View {
// First Try
//@ObservedObject private var watchManager = WatchManager()
// Second and Third Try
@StateObject private var watchManager = WatchManager()
@StateObject private var myViewModel = ViewModel(watchManager: WatchManager())
var body: some View {
HStack {
// Is needed for user information
Text("Distance: \(watchManager.deltaDistance)")
}
.padding()
HStack {
Text("Distance2: \(myViewModel.deltaDistance2)")
Button("set DeltaDistance2") {
myViewModel.setWithOtherDistance()
}
}
.padding()
}
}
extension RecordView {
@MainActor class ViewModel: ObservableObject {
// First Try
//@StateObject private var watchManager2 = WatchManager()
//Second Try
//@ObservedObject private var watchManager2 = WatchManager()
// Third Try
private var watchManager: WatchManager
init(watchManager: WatchManager) {
self.watchManager = watchManager
}
@Published var deltaDistance2 = 0.0
func setWithOtherDistance() {
deltaDistance2 = watchManager.deltaDistance
}
}
}
class WatchManager: ObservableObject {
@Published var deltaDistance = 0.0
func setDistance() {
self.deltaDistance = 9.0
}
}
At first I tried to only have one @StateObject in my extension, but then no value changed at all.
Second I tried to make an @StateObject in the RecordView and an @ObservableObject in my extension. This didn’t work either.
At last I tried to share the watchManager-instance from the RecordView into the extension. But this didn’t also work.