iOS- 具有日期类型属性的非存档NSSecureCoding对象

问题描述 投票:1回答:1
   @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变量)时,发生致命错误。这是控制台的消息。

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。一切顺利。

ios nscoding nskeyedarchiver
1个回答
2
投票

documentation for NSSecureCoding

覆盖NSSecureCoding的对象必须解码所有包含的内容使用init(coder:)方法的对象。例如:

decodeObjectOfClass:forKey:

您应该在实现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

© www.soinside.com 2019 - 2024. All rights reserved.