将 NSDictionary 设置为 UserDefaults 时出现异常

Exception while setting NSDictionary to UserDefaults

如何修复异常:

[User Defaults] Attempt to set a non-property-list object {
4 = 5;
} as an NSUserDefaults/CFPreferences value for key MyKey

通过执行以下代码抛出 (Swift 3)

let ns = NSDictionary(dictionary: [4: 5])
UserDefaults.standard.set(ns, forKey: "MyKey")

上面的代码正确保存了 String 类型,但是 NSDictionary

有问题

您的词典必须有字符串作为键,您才能将其保存到 UserDefaults

这对我有用:

let ns = NSDictionary(dictionary: ["4": 5])
UserDefaults.standard.set(ns, forKey: "MyKey")

所有 属性 列表键都必须是 String

来自documentation

And although NSDictionary and CFDictionary objects allow their keys to be objects of any type, if the keys are not string objects, the collections are not property-list objects.

let ns = ["4": 5]
UserDefaults.standard.set(ns, forKey: "MyKey")

无需使用 NSDictionary,Swift Dictionary 的工作方式相同并且被隐式桥接。