3

我一直在寻找这个问题的答案,但我找不到任何答案,类似的根本没有答案。基本上,我想用 NSKeyedUnarchiver.archiveRootObject() 保存数据并用 .unarchiveObject(withFile) 加载它。它在 Swift 2.3 上运行良好,现在它崩溃了,说非归档部分总是返回 nil。我还会检查该文件是否存在并且确实存在。我真的不知道发生了什么。这是加载过程:

func loadnotifs(_ username:String)->[AFNotificationData]{
    let ArchiveURL = Constants.DocumentsDirectory.appendingPathComponent(username)
        print("loading " + ArchiveURL.path)
    if FileManager.default.fileExists(atPath: ArchiveURL.path) {
        let unarchived = NSKeyedUnarchiver.unarchiveObject(withFile: ArchiveURL.path) as? [AFNotificationData]
        if unarchived != nil {
            return  NSKeyedUnarchiver.unarchiveObject(withFile: ArchiveURL.path) as! [AFNotificationData]
        } else {
            return []
        }
    }
    else {
        return []
    }

}

这是节省:

func savenotifs(_ username:String){
    if username != "" {
        let ArchiveURL = Constants.DocumentsDirectory.appendingPathComponent(username)
        print("saving " + ArchiveURL.path)
       }

        let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(AFDatabase.sharedDatabase.notificationList, toFile: ArchiveURL.path)
        if !isSuccessfulSave {
            print("Failed to save notifs")
        }

    }
}

但最后我总是得到“致命错误:在展开可选值时意外发现 nil”

4

1 回答 1

6

我找错地方了。实际上保存和加载过程很好,问题是遵守 NSCoding 协议所需的初始化:我正在使用

aDecoder.decodeObject(forKey:xxx) as! Bool

而不是新的

aDecoder.decodeBool(forKey:xxx)

考虑到它是由 swift 2.3->3 转换器使用错误的命令自动更改的,请注意这一点!

此外,请注意,因为此命令与 swift 2.3 中的布尔值/整数不兼容。

于 2016-10-03T11:23:00.437 回答