简体   繁体   English

Swift - UserDefaults 设置未保存在框架内

[英]Swift - UserDefaults setting not getting saved inside framework

I have a framework that is generating a device UUID once and saving it using UserDefaults.我有一个框架,它生成一次设备 UUID 并使用 UserDefaults 保存它。 The app has access to the UserDefaults and everything works as expected.该应用程序可以访问 UserDefaults 并且一切都按预期工作。 However, the framework is not accessing UserDefaults in some cases.但是,在某些情况下,框架不会访问 UserDefaults。 I sorted this out on an iPhone 8 using the synchronize() method:我在 iPhone 8 上使用 synchronize() 方法解决了这个问题:

  func getDeviceID() -> String {
      if let device = UserDefaults.standard.object(forKey: "DeviceID") as? String {
           return device
       } else {
           let device = UUID().uuidString
           UserDefaults.standard.set(device, forKey: "DeviceID")
           UserDefaults.standard.synchronize() // this line helped with an iPhone 8
           return device
       }
   }

However, on an older iPhone SE 1st generation the issue comes back.但是,在较旧的第一代 iPhone SE 上,问题又回来了。 First, why is this happening at all, and why is the synchronize() method seemingly helping in a newer device?首先,为什么会发生这种情况,为什么 synchronize() 方法似乎有助于更新设备? (Both phones are running iOS 13) Are there any known limitations when accessing UserDefaults from within a framework? (两部手机都运行 iOS 13)从框架内访问 UserDefaults 时是否有任何已知限制?

If it is failing when you're reading data right after writing the deviceId to UserDefaults Then it could be related to how UserDefaults actually stores the data to disk.如果在将 deviceId 写入 UserDefaults 后立即读取数据时失败,则可能与 UserDefaults 实际将数据存储到磁盘的方式有关。

The actual write to disk is asynchronous and batched automatically by NSUserDefaults.实际写入磁盘是异步的,并且由 NSUserDefaults 自动批处理。 Check this检查这个

So there's a chance that it is slower for older devices running new iOS versions.因此,运行新 iOS 版本的旧设备可能会变慢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM