Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
320 views
in Technique[技术] by (71.8m points)

ios - 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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())

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...