ios - NSKeyedArchiver 返回 nil Swift 4.2

标签 ios swift persistence nskeyedarchiver nscoder

 let lessons = Lessons(definition: "testo", photo: url)
 SaveUtil.saveLessons(lessons: lessons!)
 let x = SaveUtil.loadLessons()

所以一切都编译并运行,但 x 为零....我正在尝试使此 ios12/swift 4.2 兼容,但不知道缺少什么。谢谢!

class SaveUtil {
    static func saveLessons(lessons: Lessons) {
        let data = try! NSKeyedArchiver.archivedData(withRootObject: lessons, requiringSecureCoding: false)
        UserDefaults.standard.set(data, forKey: "lessons")
    }

    static func loadLessons() -> [Lessons]?  {

        let data = UserDefaults.standard.data(forKey: "lessons")
        return try! NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data!) as? [Lessons]
    }
}

最佳答案

loadSession 返回一组 Lesson。 “作为?”将检查类型。由于未归档的对象不是数组,它将返回 nil。您正在将其存档为类(class)对象并将其取消存档为类(class)数组对象。

static func loadLessons() -> Lessons?  {

        let data = UserDefaults.standard.data(forKey: "lessons")

        return try! NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data!) as? Lessons
    }

下面是有效的代码。

class Lessons : NSObject,NSCoding {

    var definitionText:String
    var photoURL:String

    init(definition:String,photoURL:String) {
        self.definitionText = definition
        self.photoURL = photoURL
    }

    func encode(with aCoder: NSCoder) {
        aCoder.encode(self.definitionText, forKey: "definitionText")
        aCoder.encode(self.photoURL, forKey: "photoURL")
    }

    required convenience init?(coder aDecoder: NSCoder) {
        self.init(definition: "", photoURL: "")
        self.definitionText = aDecoder.decodeObject(forKey: "definitionText") as! String
        self.photoURL = aDecoder.decodeObject(forKey: "photoURL") as! String
    }
}
class SaveUtil {
    static func saveLessons(lessons: Lessons) {

        let data = NSKeyedArchiver.archivedData(withRootObject: lessons)
        UserDefaults.standard.set(data, forKey: "lessons")
    }

    static func loadLessons() -> Lessons?  {
        let data = UserDefaults.standard.data(forKey: "lessons")
        return try! NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data!) as? Lessons
    }
}

运行代码后,它将返回对象。

let lessons = Lessons(definition: "testo", photoURL: "photo.jpg")
        SaveUtil.saveLessons(lessons: lessons)
        let x = SaveUtil.loadLessons()
        print("\(x?.photoURL)")

关于ios - NSKeyedArchiver 返回 nil Swift 4.2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52509172/

相关文章:

iphone - 使用 safari 或 map 打开 map

ios - 慢慢地推ViewController

ios - 如何在运行时正确压缩 UIImages

python - 您将什么称为允许持久操作的非持久数据结构?

java - 错误 : Class "test2" is mapped, 但不包含在任何

iOS:我能否以编程方式决定与哪个组件交互(滚动)?

ios - 使用适用于 iOS 的 Google Maps SDK 后应用程序大小增加

ios - 在 swift 3 中使用 UISearchBar/UISearchController 进行即时搜索

ios - NSFetchedResultsController 与像 iMessage 的表

用于管理数据库外部的 BLOB 数据的 Java 框架