我的应用需要代表一组预设,其中预设由以下结构表示:
struct Preset: Codable {
var name: String
var value: Int
}
使用NSUserDefaultsController
,NSTableView
和CocoaBindings,我可以创建一个“首选项”窗口,可以在其中添加和删除预设以及对其进行编辑。它们被持久保存到UserDefaults
plist中,如下所示:
<plist version="1.0">
<dict>
<key>presets</key>
<array>
<dict>
<key>name</key>
<string>A preset</string>
<key>value</key>
<integer>1</integer>
</dict>
<dict>
<key>name</key>
<string>Another preset</string>
<key>value</key>
<integer>2</integer>
</dict>
</array>
</dict>
</plist>
我正在寻找使用自然符号在代码中访问此数据的方法。基本上,我想让“设置”单例具有这样的计算属性:
class Settings: NSObject {
static let sharedInstance = Settings()
private let presetsKey = "presets"
override private init() {
UserDefaults.standard.register(defaults: [
presetsKey: [ ["name": "Default preset", "value": 0] ],
])
super.init()
}
var presets: [Preset] {
get {
// Missing code goes here
}
}
}
getter中的代码应执行从preset
UserDefaults
数组到[Preset]
的映射,以代替// Missing code goes here
注释。这是我要使用的符号的示例:
let firstPresetName = Settings.sharedValue.preset[0].name
let firstPresetValue = Settings.sharedValue.preset[0].value
print("The first preset's name is \(firstPresetName\) and its value is \(firstPresetValue\)")
我写了这个,它有效:
let presets = UserDefaults.standard.array(forKey: presetsKey) as! [[String: Any]]
var result = [Preset]()
for preset in presets {
result.append(ControlParameters(name:preset["name"] as! String, value:preset["value"] as! Int))
}
return result
但是我对这种解决方案不满意。是否有一个更紧凑,更通用的解决方案(它可以在相似的上下文中适用于任何结构,而不必对诸如name
和value
这样的结构属性名称进行硬编码)?
答案 0 :(得分:1)
您可以使用PropertyListDecoder
直接解码属性列表文件:
struct Preset: Codable {
var name: String
var value: Int
}
struct Presets : Codable {
let presets: [Preset]
}
let decoder = PropertyListDecoder()
let presets = try? decoder.decode(Presets.self, from: yourPropertyListData)
答案 1 :(得分:-1)
通过gist,我进行了一些修改即可解决该问题:
extension UserDefaults {
func encode<T: Encodable>(_ value: T?, forKey key: String) throws {
switch T.self {
case is Float.Type, is Double.Type, is String.Type, is Int.Type, is Bool.Type:
set(value!, forKey: key)
default:
let data = try value.map(PropertyListEncoder().encode)
let any = data.map { try! PropertyListSerialization.propertyList(from: $0, options: [], format: nil) }
set(any, forKey: key)
}
}
func decode<T: Decodable>(_ type: T.Type, forKey key: String) throws -> T? {
switch T.self {
case is Float.Type, is Double.Type, is String.Type, is Int.Type, is Bool.Type:
return (value(forKey: key) as! T)
default:
let any = object(forKey: key)
let data = any.map { try! PropertyListSerialization.data(fromPropertyList: $0, format: .binary, options: 0) }
return try data.map { try PropertyListDecoder().decode(type, from: $0) }
}
}
}
以此,我可以定义以下通用函数:
private func getter<T: Codable>(key: String) -> T {
let result = try! UserDefaults.standard.decode(T.self, forKey: key)
return result!
}
private func setter<T: Codable>(_ newValue: T, forKey key: String) {
try! UserDefaults.standard.encode(newValue, forKey: key)
}
现在我可以为我的所有属性实现计算的getter和setter方法:
var presets: [Preset] {
get {
return getter(presetsKey)
}
set {
setter(newValue, presetsKey)
}
}
它也适用于非数组类型。