2014-11-21 72 views
1

我想使用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类。

+2

你是如何编码'savedData'? – rintaro 2014-11-21 15:23:44

+0

更新了代码以反映savedData。 – 2014-11-21 15:30:02

+0

看起来写入可能会失败,读取时会导致零长度数据。有两件事很值得了解:(1)你如何获得你正在使用的URL,它的路径是什么? (2)当你调用'writeToURL'时,'success'的值是多少? – 2014-11-21 19:01:48

回答

1

您的NSCoding代码看起来不错,但是您的归档方法与我的看起来不一样。尝试使用此代码示例来存档您的数据。下面是我使用的代码示例存储我已经在迅速

func saveCustomData(data : NSMutableArray) 
    { 
     var filemgr : NSFileManager 
     var docsDir : String 
     var dirPaths : NSArray 

     filemgr = NSFileManager.defaultManager() 

     dirPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray 
     docsDir = dirPaths[0] as NSString 
     var dataFilePath = docsDir.stringByAppendingPathComponent("data.archive") 

     NSKeyedArchiver.archiveRootObject(data, toFile: dataFilePath) 
    } 

创建然后当你想解除封存,使用此

func loadCustomData() -> NSMutableArray 
    { 
     var filemgr : NSFileManager 
     var docsDir : String 
     var dirPaths : NSArray 

     filemgr = NSFileManager.defaultManager() 
     dirPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray 
     docsDir = dirPaths[0] as NSString 

     var dataFilePath = docsDir.stringByAppendingPathComponent("data.archive") 
     if(filemgr.fileExistsAtPath(dataFilePath)) 
     { 
      var journeyData = NSKeyedUnarchiver.unarchiveObjectWithFile(dataFilePath) as NSMutableArray 
      return journeyData 
     } 
     else 
     { 
      var emptyArray = NSMutableArray() 
      return NSMutableArray() 
     } 
    } 

希望帮助一个自定义类的mutablearray,如果你有任何问题,随时问

+0

谢谢!我使用NSFileCoordinator出于不同的原因,这就是为什么我的存档代码是不同的。 – 2014-11-21 15:39:26