我想将结构用于我的应用程序的(非常简单的)模型。
但是NSKeyedArchiver
只接受对象(扩展NSObjects
)。
有没有什么好方法可以将结构保存到文件中?
答案 0 :(得分:5)
我有时会使用一种非常简单的方法。您需要编写的代码数量不多于类/ NSCoding方案。
首先导入伟大的SwiftyJSON lib。
struct Starship {
let name: String
let warpSpeed: Bool
let captain: String?
init(name: String, warpSpeed: Bool, captain: String? = nil) {
self.name = name
self.warpSpeed = warpSpeed
self.captain = captain
}
}
struct Starship {
let name: String
let warpSpeed: Bool
let captain: String?
init(name: String, warpSpeed: Bool, captain: String? = nil) {
self.name = name
self.warpSpeed = warpSpeed
self.captain = captain
}
init?(json: JSON) {
guard let
name = json["name"].string,
warpSpeed = json["warpSpeed"].bool
else { return nil }
self.name = name
self.warpSpeed = warpSpeed
self.captain = json["captain"].string
}
var asJSON: JSON {
var json: JSON = [:]
json["name"].string = name
json["warpSpeed"].bool = warpSpeed
json["captain"].string = captain
return json
}
}
let enterprise = Starship(name: "Enteriprise D", warpSpeed: true, captain: "JeanLuc Picard")
let json = enterprise.asJSON
let data = try! json.rawData()
// save data to file and reload it
let newJson = JSON(data: data)
let ship = Starship(json: newJson)
ship?.name // "Enterprise D"