1
我保存的自定義對象Bottle
用下面的代碼對象保存的NSKeyedArchiver和加載回零是
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()
,但它不會改變任何東西,我裝的對象仍然是零。
謝謝!它完美的作品! – magohamoth
完美:D +1 Tks。 :) –