我用以下代码保存一个自定义对象
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瓶。最后两个
Bottle
打印我println
和3
所以我的数组中确实有3个元素,但它们是零,我不明白为什么。我有另一个类,它保存nil
而不是String
,它没有像Bottle
那样的init
函数,而且工作得很好。以下是我保存瓶子的方法:
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()
我也已经尝试添加了
init(id: String, title: String, year: Int, icon: UIImage)
,但它没有改变任何内容,我加载的对象仍然为零。 最佳答案
您需要在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)
}