我使用以下代码保存自定义对象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个元素,但它们是零,我不明白为什么。我有另一个课程可以保存String
而不是Bottle
而且没有像init
这样的init(id: String, 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()
,但它没有改变任何内容,我加载的对象仍为零。
答案 0 :(得分:3)
您需要在Bottle
方法中保存并检索所有 NSCoding
的属性:
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)
}