gpt4 book ai didi

ios - NSKeyedArchiver 返回 nil Swift 4.2

转载 作者:可可西里 更新时间:2023-11-01 00:54:34 24 4
gpt4 key购买 nike

 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com