2014-11-16 22 views
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打印我3nil因此,我的數組中確實有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(),但它不會改變任何東西,我裝的對象仍然是零。

回答

3

您需要保存和檢索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) 
} 
+0

謝謝!它完美的作品! – magohamoth

+0

完美:D +1 Tks。 :) –

相關問題