在我的SceneDelegate中,我指定UserInfo()的变量token:
SceneDelegate.swift

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?
    @ObservedObject var userInfo = UserInfo()

func sceneWillEnterForeground(_ scene: UIScene) {
    // Called as the scene transitions from the background to the foreground.
    // Use this method to undo the changes made on entering the background.
    InstanceID.instanceID().instanceID { (result, error) in
      if let error = error {
        print("ERROR fetching remote instance ID: \(error)")
      } else if let result = result {
        print("REMOTE instance ID token: \(result.token)")
        self.userInfo.token = result.token
      }
    }
Model.swift
class UserInfo: ObservableObject {
    @Published var token: String? = nil{
        didSet(newValue){
            print("NEW value:\(newValue)")
        }

    }
}
print("NEW value:\(newValue)")然后成功打印新值。但是,当我在另一个模型中访问token时,它是nil:
class Search: ObservableObject {
    let db = Firestore.firestore()
    lazy var functions = Functions.functions()
    let settings = UserSettings()
    @ObservedObject var userInfo = UserInfo()
    @ObservedObject var locationManager = LocationManager()
    @Published var status = Status.offline

    func getUserData() -> [String:Any?]? {
        guard let birthday = UserDefaults.standard.string(forKey: "birthday"), let latitude = locationManager.location?.coordinate.latitude, let longitude = locationManager.location?.coordinate.longitude else {
            print("BDAY \(UserDefaults.standard.string(forKey: "birthday"))")
            print("LOCATION \(locationManager.location?.coordinate.latitude)")
            print("TOKEN \(self.userInfo.token)") // prints nil
            return nil
        }
        guard let fcmToken = self.userInfo.token else {
            return nil
        }
为什么是这样?在应用启动时,userInfo.token仅在SceneDelegate中分配一次-所以我不确定为什么它的值更改为nil。除非存在UserInfo()的多个实例-但是我认为ObservableObject会使其成为“真理的一个来源”?

最佳答案

第一:@ObservedObject仅在SwiftUI View中有意义,因此只需从类中删除该包装即可。
2nd:您的SceneDelegateSearch创建了UserInfo的不同实例,因此很明显,更改其中一个实例不会对另一实例产生影响。
解决方案:从提供的快照尚不清楚Search如何引用SceneDelegate,但是您必须以某种方式将SceneDelegate.userInfo注入Search来代替后者(通过构造函数参数或通过分配属性)

10-07 17:36