【问题标题】:How can I check UserDefaults after terminate and reopen an app in Xcode (swift)如何在 Xcode 中终止并重新打开应用程序后检查 UserDefaults (swift)
【发布时间】:2018-01-17 14:24:49
【问题描述】:

我归档了一个采用 Codable 的对象,实现了在应用进入后台时存储对象数据,在应用重新打开时加载它们。

但它不起作用。

终止并重新打开模拟器后如何检查 UserDefaults 的更改?

我制作了“Machine”类 Codable,并实现了“MachineStore”类来归档 Machine 对象。

保存数据:

func saveChanges() {
    var data = Data()
    do {
        data = try encoder.encode(self.machine)
    } catch {
        NSLog(error.localizedDescription)
    }
    UserDefaults.standard.set(data, forKey: MachineStore.Key)
}

加载数据:

func loadMachine() {
    guard let data = UserDefaults.standard.data(forKey: MachineStore.Key) else { return }
    do {
        machine = try decoder.decode(VendingMachine.self, from: data)
    } catch {
        NSLog(error.localizedDescription)
    }
}

我在 AppDelegate 中使用了 MachineStore。

let machineStore: MachineStore = MachineStore()

func application(_ application: UIApplication,
                 didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    machineStore.loadMachine()
    return true
}

func applicationDidEnterBackground(_ application: UIApplication) {
    machineStore.saveChanges()
}

【问题讨论】:

  • 能不能也贴一些相关的代码
  • 当问题陈述很简单时,很难提供解决方案,"it doesn't work"。请edit您的问题更完整地描述您预期会发生什么以及这与实际结果有何不同。请参阅 How to Ask 以获取有关什么是好的解释的提示。
  • 您需要为 UserDefaults 使用编码器和解码器,因为您正在处理自定义类对象
  • 我让 VendingMachine 类采用 Codable 协议。

标签: ios swift archive codable userdefaults


【解决方案1】:

之前对您的对象进行编码/解码。例如,您可以使用以下代码:

extension UserDefaults {
    func persist<Value>(_ value: Value, forKey key: String) where Value : Codable {
        guard let data = try? PropertyListEncoder().encode(value) else { return }
        set(data, forKey: key)
    }

    func retrieveValue<Value>(forKey key: String) -> Value? where Value : Codable {
        return data(forKey: key).flatMap { try? PropertyListDecoder().decode(Value.self, from: $0) }
    }
}

【讨论】:

    猜你喜欢
    • 2017-07-09
    • 2019-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-02
    • 2017-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多