ios – On storing a binding in an Observable object in SwiftUI

[ad_1]

I am creating a Mac-App. When it is launched multiple times all windows should access the same application-state (theAppState) but each window should display its own data (of kind MyClass).

As is shown below, when the MainWindow creates the MyClass-object it passes the binding to theAppState.

The MainWindow has a button that invokes obj.incBoth(). As a result, theAppState is increased (as it should).

The body shows theAppState in the different ways:

  1. self.appState is displayed correctly and it is increased on each button press.
  2. obj.appstate is not displayed correctly (the original value 42 is always shown)
  3. obj.appstate() is not displayed correctly (same as obj.appstate)

Pleaase help me understand this strange behaviour!

import SwiftUI

class MyClass : ObservableObject {
    @Published var x = 0
    @Binding var appstate : Int
    
    init(appstate : Binding<Int> ){
        self._appstate = appstate
    }
    
    func appstate2() -> Int {
        return self.appstate
    }
    func incBoth() {
        x+=1
        appstate += 1
        print("x=\(x) appstate=\(appstate)")
    }
}

struct MainView : View {
    @Binding var appState : Int
    @StateObject var obj : MyClass
    
    init(appstate: Binding<Int>){
        self._appState = appstate
        self._obj = StateObject(wrappedValue: MyClass(appstate: appstate))
    }
    
    var body: some View {
        Text("appState = \(appState),  obj.appstate = \(obj.appstate), obj.appstate2 = \(obj.appstate2())   obj.x = \(obj.x)")
        Button("Inc") {
            obj.incBoth()
        }
    }
}

@main
struct ProblemApp : App {
    @State private var theAppState = 42
    
    var body: some Scene {
        WindowGroup {
            MainView(appstate: $theAppState)
        }
    }
}

[ad_2]

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top