NSKeyedArchiver返回nil Swift 4.2

时间:2018-09-26 02:38:28

标签: 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]
    }
}

1 个答案:

答案 0 :(得分:2)

loadSession返回一个Lesson数组。 “如?”将检查类型。由于未归档的对象不是数组,因此它将返回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
    }
}

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

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