NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

[Solved: pilot error] Can compile with @StateObject, but it doesn't work at runtime

Forums > SwiftUI

Per @Hatsushira's suggesstion, I moved the init of both objects into my initializer. Compiles fine, but now I can't get any notifications. I've tried various different permutations, most of which don't compile, some of which compile but then complain at runtime about the object being referenced while not being installed on a view--another error message I can barely grasp. Welcoming any suggestions, cheers.

@main
struct ArkansasApp: App {
    @StateObject var appState: AppState
    @StateObject var arkansasScene: ArkansasScene

    init() {
        let state = AppState()
        let scene = ArkansasScene(appState: state)

        _appState = StateObject(wrappedValue: state)
        _arkansasScene = StateObject(wrappedValue: scene)
    }

    var body: some Scene {
        WindowGroup {
            ContentView()
                .environmentObject(appState)
                .environmentObject(arkansasScene)
        }
    }
}

class AppState: ObservableObject {
    @Published var numberOfStopSignsInArkansas = 400000
}

class ArkansasScene: SKScene, SKSceneDelegate, ObservableObject {
    @ObservedObject var appState: AppState

    var stopSignObserver: AnyCancellable!

    let side: Double = 1024

    init(appState: AppState) {
        self._appState = ObservedObject(initialValue: appState)

        super.init(size: CGSize(width: side, height: side))

        ping()
    }

    func ping() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            [weak self] in guard let myself = self else { return }
            myself.appState.numberOfStopSignsInArkansas += 1
            print("new value \(myself.appState.numberOfStopSignsInArkansas)")
            myself.ping()
        }
    }

    override func didMove(to view: SKView) {
        stopSignObserver = appState.$numberOfStopSignsInArkansas.sink {
            print("Got notification \($0)")
        }
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

I didn't instantiate the view that contains ArkansasScene πŸ€¦β€β™‚οΈ

1      

Hacking with Swift is sponsored by Essential Developer

SPONSORED From March 20th to 26th, you can join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer!

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.