NSKeyedArchiver 返回 nil Swift 4.2

NSKeyedArchiver returning nil Swift 4.2

 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 return是一组 Lesson。 "as?" 将检查类型。由于未归档的对象不是数组,因此它将 return nil。您正在将其存档为课程对象并将其取消存档为课程数组对象。

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

之后你 运行 你的代码它将 return 对象。

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