我使用以下代码保存自定义对象 Bottle
class Bottle: NSObject, NSCoding {
let id: String!
let title: String!
let year: Int!
let icon: UIImage!
init(id: String, title: String, year: Int, icon: UIImage) {
self.id = id
self.title = title
self.year = year
self.icon = icon
}
override init(){}
var bottlesArray = NSMutableArray()
// code inspired from http://stackoverflow.com/questions/24238868/swift-nscoding-not-working
required init(coder aDecoder: NSCoder) {
self.bottlesArray = aDecoder.decodeObjectForKey("bottleArray") as NSMutableArray
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(bottlesArray, forKey: "bottleArray")
}
func add(bottle: Bottle) {
self.bottlesArray.addObject(bottle)
}
func save() {
let data = NSKeyedArchiver.archivedDataWithRootObject(self)
NSUserDefaults.standardUserDefaults().setObject(data, forKey: "bottleList")
}
class func loadSaved() -> Bottle? {
if let data = NSUserDefaults.standardUserDefaults().objectForKey("bottleList") as? NSData {
return NSKeyedUnarchiver.unarchiveObjectWithData(data) as? Bottle
}
return nil
}
func saveBottle(bottle: Bottle) {
let bottleList = Bottle.loadSaved()
bottleList?.add(bottle)
bottleList?.save()
let bottleList2 = Bottle.loadSaved()
println(bottleList2?.bottlesArray.count)
println(bottleList2?.bottlesArray[0].title)
}
}
我节省了 3 瓶。最后两个 println 打印 3 和 nil 所以我的数组中确实有 3 个元素,但它们是 nil,我不明白为什么。我有另一个类保存 String 而不是 Bottle 并且没有像 init(id: String) 这样的 一个,它工作正常。init 函数, title: String, year: Int, icon: UIImage)
以下是我如何保存我的瓶子:
var bottleLoaded = Bottle.loadSaved()!
var bottleToSave = Bottle(id: bottleID, title: bottleName, year: bottleYear, icon: UIImage(data:bottleIconData)!)
bottleLoaded.saveBottle(bottleToSave)
就是这样。
为了“初始化”内存,我在之前的 ViewController 中也有以下代码
let bottleList = Bottle()
bottleList.save()
我也已经尝试添加 NSUserDefaults.standardUserDefaults().synchronize() 但它没有改变任何东西,我加载的对象仍然是零。
请您参考如下方法:
您需要在 NSCoding 方法中保存和检索 所有 Bottle 的属性:
required init(coder aDecoder: NSCoder) {
self.bottlesArray = aDecoder.decodeObjectForKey("bottleArray") as NSMutableArray
self.id = aDecoder.decodeObjectForKey("id") as String
//etc. same for title, year, and icon (use decodeIntegerForKey: for year)
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(bottlesArray, forKey: "bottleArray")
aCoder.encodeObject(self.id, forKey: "id")
//etc. same for title, year, and icon (use encodeInteger:forKey: for year)
}
