我想使用NSKeyedUnarchiver類來解壓我的自定義對象,並不斷收到錯誤。NSCoding在Swift中不工作
Terminating app due to uncaught exception 'NSInvalidUnarchiveOperationException', reason: '*** -[NSKeyedUnarchiver decodeObjectForKey:]: cannot decode object of class (HelloAppleWatch.Note)'
用於說明類的代碼如下所示:
import UIKit
class Note: NSObject,NSCoding {
var title :String?
override init() {}
required init(coder aDecoder: NSCoder) {
self.title = aDecoder.decodeObjectForKey("title") as String?
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(self.title, forKey: "title")
}
}
用於取消歸檔的代碼如下所示:
let savedData = NSData(contentsOfURL: newURL)
let note = NSKeyedUnarchiver.unarchiveObjectWithData(savedData!) as Note?
UPDATE:
func createNote() {
let note = Note()
note.title = self.noteTextField?.text
// archive the note object
let fileCoordinator = NSFileCoordinator(filePresenter: self)
fileCoordinator.coordinateWritingItemAtURL(presentedItemURL!, options: nil, error: nil) { (newURL :NSURL!) -> Void in
let saveData = NSKeyedArchiver.archivedDataWithRootObject(note)
let success = saveData.writeToURL(newURL, atomically: true)
}
}
奇怪的是,當unarchive decodeObjectForKey被觸發時,它甚至不會去執行Note.swift類。
你是如何編碼'savedData'? – rintaro 2014-11-21 15:23:44
更新了代碼以反映savedData。 – 2014-11-21 15:30:02
看起來寫入可能會失敗,讀取時會導致零長度數據。有兩件事很值得了解:(1)你如何獲得你正在使用的URL,它的路徑是什麼? (2)當你調用'writeToURL'時,'success'的值是多少? – 2014-11-21 19:01:48