iOS-具有日期类型属性的非归档NSSecureCoding对象
iOS-具有日期类型属性的非归档NSSecureCoding对象,ios,nscoding,nskeyedarchiver,Ios,Nscoding,Nskeyedarchiver,EventNotificationInfo对象的实例 @objc(EventNotificationInfo) class EventNotificationInfo: NSObject, NSSecureCoding { public var name: String public var startTime: Date public var hexColor: String init(name: String,
EventNotificationInfo
对象的实例
@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
}
}
使用以下代码,我归档并取消归档上述对象
let event = EventNotificationInfo(name: "Hello from California",
startTime:Date(),
hexColor: "000000")
当xCode到达我在最后一行设置的断点(unArchive
variable)时,会发生致命错误。这是控制台的消息
let eventInfo = try? NSKeyedArchiver.archivedData(withRootObject: event, requiringSecureCoding: false)
let unArchive = try! NSKeyedUnarchiver.unarchivedObject(ofClass: TPEventNotificationInfo.self, from: eventInfo!)
有什么问题吗?如何取消此对象的归档?
信息:我使用了
String
类型的startTime
。而且进展顺利 根据:
重写init(coder:)
的对象必须解码任何包含的
使用decodeObjectOfClass:forKey:
方法的对象。例如:
let obj=decoder.decodeObject(of:MyClass.self,forKey:“myKey”)
您应该在init(coder:)
的实现中这样做
另外,不要使用try
,您应该将其包装在一个do
/catch
中,以便查看是否发生错误
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
guard let startTime = coder.decodeObject(of: NSDate.self, forKey: Keys.startTime) as Date? else {
return nil
}