gpt4 book ai didi

iOS - 取消归档具有日期类型属性的 NSSecureCoding 对象

转载 作者:行者123 更新时间:2023-12-01 19:35:41 26 4
gpt4 key购买 nike

   @objc(EventNotificationInfo)
class EventNotificationInfo: NSObject, NSSecureCoding {
public var name: String
public var startTime: Date
public var hexColor: String

init(name: String, startTime: Date, hexColor: String) {
self.name = name
self.startTime = startTime
self.hexColor = hexColor
}

private struct Keys {
static var name: String = "name"
static let startTime: String = "startTime"
static let hexColor: String = "hexColor"
}

static var supportsSecureCoding: Bool = true

func encode(with coder: NSCoder) {
coder.encode(name, forKey: Keys.name)
coder.encode(startTime, forKey: Keys.startTime)
coder.encode(hexColor, forKey: Keys.hexColor)
}

required init?(coder: NSCoder) {
guard let name = coder.decodeObject(forKey: Keys.name) as? String else {
return nil
}

guard let startTime = coder.decodeObject(forKey: Keys.startTime) as? Date else {
print("You are here")
return nil
}

guard let color = coder.decodeObject(forKey: Keys.hexColor) as? String else {
return nil
}
self.name = name
self.startTime = startTime
self.hexColor = color
}
}
EventNotificationInfo 的一个实例目的。
let event = EventNotificationInfo(name: "Hello from California",
startTime:Date(),
hexColor: "000000")

使用以下代码,我归档和取消归档上述对象。
let eventInfo  = try? NSKeyedArchiver.archivedData(withRootObject: event, requiringSecureCoding: false)


let unArchive = try! NSKeyedUnarchiver.unarchivedObject(ofClass: TPEventNotificationInfo.self, from: eventInfo!)

当 xCode 到达我在最后一行( unArchive 变量)设置的断点时,会发生 fatal error 。这是控制台的消息。
You are here.
Fatal error: 'try!' expression unexpectedly raised an error: Error Domain=NSCocoaErrorDomain Code=4864 "value for key 'startTime' was of unexpected class 'NSDate'. Allowed classes are '{(
EventNotificationInfo
)}'." UserInfo={NSDebugDescription=value for key 'startTime' was of unexpected class 'NSDate'. Allowed classes are '{(
EventNotificationInfo
)}'.}: file

可能是什么问题呢?如何取消归档此对象?

信息:我用过 startTime类型 String .它进展顺利。

最佳答案

根据 documentation for NSSecureCoding :

An object that does override init(coder:) must decode any enclosed objects using the decodeObjectOfClass:forKey: method. For example:

let obj = decoder.decodeObject(of:MyClass.self, forKey: "myKey")



你应该在你的 init(coder:) 的实现中这样做。 .
guard let startTime = coder.decodeObject(of: NSDate.self, forKey: Keys.startTime) as Date? else {
return nil
}

此外,不要使用 try! , 你应该把它包在 do/ catch以便您查看是否发生错误。

关于iOS - 取消归档具有日期类型属性的 NSSecureCoding 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60253397/

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