无法在Swift3中检索正确保存的NSKeyArchived对象

时间:2017-03-20 20:22:30

标签: ios swift swift3 nskeyedarchiver nskeyedunarchiver

我无法检索在Swift 3中保存为NSkeyed存档的对象,并且正在吓唬我的脑袋。该对象已成功保存为plist,但在重新加载时返回为nil。

以下是我使用的代码:

要保存为对象的类本身非常简单:

import Foundation

class ItemList:NSObject, NSCoding {

    var name: String = "" //Name of the Item list
    var contents: [Int] = [] //Ints referencing the CoreData PackItems

    init (listname:String, ContentItems:[Int]) {
        self.name=listname
        self.contents=ContentItems
    }

    //MARK: NSCoding
    public convenience required init?(coder aDecoder: NSCoder) {
        let thename = aDecoder.decodeObject(forKey: "name") as! String
        let thecontents = aDecoder.decodeObject(forKey: "contents") as! [Int]
        self.init(listname: thename,ContentItems: thecontents)
    }

    func encode(with aCoder: NSCoder) {
        aCoder.encode(self.name,forKey:"name")
        aCoder.encode(self.contents, forKey: "contents")
    }

}

加载和保存对象的代码:

class FileHandler: NSObject {

    class func getDocumentsDirectory() -> URL {
        let filemgr = FileManager.default
        let urls = filemgr.urls(for: .documentDirectory, in: .userDomainMask)
        let result:URL = urls.first!
        return result
    }

    ///This returns the contents of the handed file inside the Documents directory as the object it was saved as.
    class func getFileAsObject(filename:String) -> AnyObject? {

        let path = getDocumentsDirectory().appendingPathComponent(filename)

        if let result = NSKeyedUnarchiver.unarchiveObject(withFile: path.absoluteString) {
            //Success
            print("Loaded file '"+filename+"' from storage")
            return result as AnyObject?
        } else {
            print("Error: Couldn't find requested object '"+filename+"' in storage at "+path.absoluteString)
            return nil
        }
    }

    ///This saves the handed object under the given filename in the App's Documents directory.
    class func saveObjectAsFile(filename:String, Object:AnyObject) {
        let data = NSKeyedArchiver.archivedData(withRootObject: Object)
        let fullPath = getDocumentsDirectory().appendingPathComponent(filename)

        do {
            try data.write(to: fullPath)
            print("Wrote file '"+filename+"' to storage at "+fullPath.absoluteString)
        } catch {
            print("Error: Couldn't write file '"+filename+"' to storage")
        }
    }

}

...最后,这就是我所说的全部:

let testobject:ItemList = ItemList.init(listname: "testlist", ContentItems: [0,0,1,2])

        FileHandler.saveObjectAsFile(filename:"Test.plist",Object:testobject)
        let tobi = FileHandler.getFileAsObject(filename:"Test.plist") as! ItemList

唉,我把它作为输出:

Wrote file 'Test.plist' to storage at file:///…/data/Containers/Data/Application/6747B038-B0F7-4B77-85A8-9EA02BC574FE/Documents/Test.plist
Error: Couldn't find requested object 'Test.plist' in storage at file:///…/data/Containers/Data/Application/6747B038-B0F7-4B77-85A8-9EA02BC574FE/Documents/Test.plist

请注意,这是我自己的输出 - 所以我做(并检查过)文件是否正确创建。但它只是不会加载。谁能告诉我我做错了什么?

1 个答案:

答案 0 :(得分:2)

问题在于您传递给unarchiveObject(withFile:)的路径。

变化:

if let result = NSKeyedUnarchiver.unarchiveObject(withFile: path.absoluteString) {

为:

if let result = NSKeyedUnarchiver.unarchiveObject(withFile: path.path) {

另外,您应该使用对称API来编写和阅读逻辑。编写数据时,将根对象存档到Data对象,然后将Data对象写入文件。但是在阅读时,您可以直接取消归档给定文件路径的对象树。

更改您的编写代码以使用archiveRootObject(_:toFile:)或更改读取代码以从文件加载Data,然后取消归档数据。您当前的代码有效(一旦修复了路径问题),但它不一致。