gpt4 book ai didi

swift - 检索自定义类时 NSKeyedUnarchiver 返回 nil

转载 作者:行者123 更新时间:2023-12-04 10:15:42 25 4
gpt4 key购买 nike

在我的 View Controller 中,我在数组中有一个自定义类存储。我使用 NSKeyedArchiver 存储数据,但我使用的是贬值版本 NSKeyedUnarchiver.unarchiveObject(withFile: object.ArchiveURL.path) as? [object] .

现在我决定将其更新为:
let data = try Data(contentsOf: filePath)
let object = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data)

这是我的保存功能:

 let data = try NSKeyedArchiver.archivedData(withRootObject: object, requiringSecureCoding: false)
try data.write(to: filePath)

当我从 Unarchiver 返回对象时,它返回 nil。我不确定为什么。
这是我的自定义类:
class object: NSObject, NSCoding {
var name: String
var photo: UIImage

struct PropertyKey {
static let name = "name"
static let photo = "photo"
}

func encode(with aCoder: NSCoder) {
aCoder.encode(self.name, forKey: PropertyKey.name)
aCoder.encode(self.photo, forKey: PropertyKey.photo)
}

required convenience init?(coder aDecoder: NSCoder) {
// The name is required. If we cannot decode a name string, the initializer should fail.
guard let name = aDecoder.decodeObject(forKey: PropertyKey.name) as? String else {
os_log("unable to find name", log: OSLog.default, type: .debug)
return nil
}

guard let photo = aDecoder.decodeObject(forKey: PropertyKey.photo) as? UIImage else {
os_log("unable to find photo", log: OSLog.default, type: .debug)
return nil
}


// Must call designated initializer.
self.init(name: name, photo: photo)
}

init?(name: String, photo: UIImage) {
// Initialize stored properties.
self.name = name
self.photo = photo

}
}

最佳答案

您可以使用此方法取消归档数据。
https://developer.apple.com/documentation/foundation/nskeyedunarchiver/2963379-unarchivedobject

NSKeyedUnarchiver.unarchivedObject(ofClasses:from:)

您可以将解档代码编写为;
let data = try Data(contentsOf: filePath)
let object = try NSKeyedUnarchiver.unarchivedObject(ofClasses:[object.self, UIImage.self], from: data)

希望它有效。

PS。关于命名类的一个提示。它们应始终以大写字母开头。

编辑:您应该在尝试取消归档时添加 UIImage.self 。
并且您应该更改存档方法,如下所示。
NSKeyedArchiver.archivedData(withRootObject: data, requiringSecureCoding: true)

使用此解档方法时,您的模型还应满足 NSSecureCoding 协议(protocol)。
extension object : NSSecureCoding {
static var supportsSecureCoding: Bool {
return true
}
}

关于swift - 检索自定义类时 NSKeyedUnarchiver 返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61070705/

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