iOS - разархивировать объект NSSecureCoding со свойством типа Date - PullRequest
1 голос
/ 17 февраля 2020
   @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. И все прошло хорошо.

1 Ответ

2 голосов
/ 17 февраля 2020

Согласно документации для 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 / catch, чтобы вы могли увидеть, если произойдет ошибка.

...