ios - 在 SceneDelegate 中分配的 Observable 属性变为 nil

标签 ios swift swiftui

在我的 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
      }
    }
模型.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 ,所以只需从您的类中删除该包装器。
第二:您的SceneDelegateSearch创建 UserInfo 的不同实例,因此很明显,更改其中一个不会影响另一个。
解决方案:从提供的快照中不清楚 Search可以引用SceneDelegate , 但你必须注入(inject) SceneDelegate.userInfo进入 Search以某种方式代替后者的创建(通过构造函数参数或通过分配属性)

关于ios - 在 SceneDelegate 中分配的 Observable 属性变为 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62618765/

相关文章:

ios - swift - `NSUnknownKeyException` : calling `setValue:forKey` on NSObject with optional values in dictionary

ios - 如何在 Swift、SpriteKit 中将矩形附加到圆形并与其一起旋转

ios - 如何更改 SwiftUI 中导航栏的背景颜色?

swiftui - 如何在 SwiftUI 中创建清晰背景的 Button

ios - SwiftUI 工作表无限显示和隐藏

ios - 滑动不显示删除按钮

objective-c - NSURL 在模拟器中为空,但在 iPad 上没问题

ios - 如何在 xcode 中克隆项目并在 ios 7 或 7+ 等中运行应用程序

swift - 如何将变量从 SecondViewController 传递到 TableViewController 中的 loadData() 函数?

php - 如何转换 Swift 日期和 TimeInterval 以便我可以发送到 php 服务器?