NSCoding在Swift中不起作用

时间:2014-11-21 15:11:07

标签: swift

我正在尝试使用NSKeyedUnarchiver类来取消归档我的自定义对象并不断收到错误。

Terminating app due to uncaught exception 'NSInvalidUnarchiveOperationException', reason: '*** -[NSKeyedUnarchiver decodeObjectForKey:]: cannot decode object of class (HelloAppleWatch.Note)'

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")
    }

}

Unarchiving的代码如下所示:

 let savedData = NSData(contentsOfURL: newURL)
            let note = NSKeyedUnarchiver.unarchiveObjectWithData(savedData!) as Note?

更新:

 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类。

1 个答案:

答案 0 :(得分:1)

您的NSCoding代码看起来不错,但您的归档方法与我的不同。尝试使用此代码示例归档数据。下面是我使用的代码示例,它存储了我在swift

中创建的自定义类的可变阵列
 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()
        }
    }

希望如果您有任何疑问,请随时提出帮助