Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't use @ObservedObject on real iPhone

i can't get my view to appear when it uses @ObservedObject in it. The app crashed when i try to present it and i get this error:

Thread 1: EXC_BAD_ACCESS (code=1, address=0x9)

The app runs fine on the simulator. It only crashes on my

iPhone 6s iOS 13 beta 6

Xcode beta 5

That's my basic code:

class NetworkManager: ObservableObject {

}

struct ContentView : View {
    @ObservedObject var networkManager: NetworkManager = NetworkManager()

    var body: some View {
        Text("Hi Stack")
    }
}

#if DEBUG
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
#endif
like image 562
SwiftiSwift Avatar asked Dec 14 '22 10:12

SwiftiSwift


1 Answers

This isn't a problem with not conforming to ObservableObject. The code you provided works in the canvas and in the simulator, and should also work on the device. I have already come across this issue with iOS 13 Beta 6 in my own project and have spent a lot of time troubleshooting.

Other things (such as calling self.presentationMode.value.dismiss() to dismiss a modal view) are also currently broken when running projects built with Xcode Beta 5 on devices running iOS 13 Beta 6. There have been issues with previous betas of Xcode not working on newer betas of iOS, and this may be the same issue.

I would suggest that you wait until Xcode Beta 6 is released to make any significant structural changes to your code, as iOS 13 Beta 6 may have been developed in anticipation of handling changes that will be made in Xcode Beta 6.

That being said, if you absolutely must make changes to workaround this issue in the meantime, I've found that using @EnvironmentObject instead of @ObservedObject fixes this issue. In your example, that would mean declaring your property like this:

@EnvironmentObject private var networkManager: NetworkManager

Then, when you create your view, you can pass a NetworkManager as an environment object like this:

ContentView()
    .environmentObject(NetworkManager())
like image 160
graycampbell Avatar answered Dec 28 '22 10:12

graycampbell