SwiftUI @EnvironmentObject error: may be missing as an ancestor of this view

后端 未结 3 707
Happy的楠姐
Happy的楠姐 2021-02-14 19:55

my first view can get all the data from API request, then opened second view to change the API request data, it crashed.

below is the error

Fatal error:          


        
3条回答
  •  隐瞒了意图╮
    2021-02-14 20:28

    This problem seems to be cause by using two instances of NetworkManager in your code.

    If you add this line to the NetworkManager:

    final class NetworkManager: … {
    
        static let shared = NetworkManager()
    
    }
    

    And then update the references in your two views like this:

    struct EarthQuakeList: … {
    
        @ObservedObject var networkManager = NetworkManager.shared
    
        …
    
    }
    
    struct EditPage: … {
    
        @ObservedObject var networkManager = NetworkManager.shared
    
        …
    
    }
    

    This will make sure both views use the exact same object to access the information. By using the same object, updates in one view will cause the other view to be updated as well.

    Once this works, I recommend to play around with .environmentObject() (example) in SwiftUI as this would allow for sharing the same instance of these service types across your application.

    Good luck with your project!

提交回复
热议问题