0

When I try to save an UIEvent-Object in NSUserDefaults, the app crashed with an error if i assign a UIEvent object.

Why? Is it possible to save an UIEvent with NSUserDefaults?

Here is my code:

extension UserDefaults {
    // UIEvent
    func event(forKey defaultName: String) -> UIEvent? {
        var event: UIEvent?
        if let eventData = data(forKey: defaultName) {
            event = NSKeyedUnarchiver.unarchiveObject(with: eventData) as? UIEvent
        }
        return event
    }

    func setEvent(_ value: UIEvent?, forKey defaultName: String) {
        var eventData: NSData?
        if let event = value {
            eventData = NSKeyedArchiver.archivedData(withRootObject: event) as NSData?
        }
        set(eventData, forKey: defaultName)
    }
}

and in the "Foil"-Class exists an UIEvent Property:

class Foil: NSObject, NSCoding {
    var event: UIEvent? {
        get {
            return UserDefaults.standard.event(forKey: "Event")
        }
        set {
            UserDefaults.standard.setEvent(newValue, forKey: "Event")
        }
    }
}
Rajamohan S
  • 7,229
  • 5
  • 36
  • 54
OnurYoruk
  • 1
  • 3
  • 1
    `UIEvent` is not `NSCoding` compliant, that's why you get the error. You can't call `NSKeyedArchiver.archivedData()` on it, because it can't call `encodeWith()`. Why do you need to do so? – Larme Aug 09 '17 at 15:28
  • I need to build a draw app where I need to save the drawn lines .. However, for me the properties of the Set and UIEvents are interesting. So a simple saving of the individual lines brings me nothing – OnurYoruk Aug 09 '17 at 15:38
  • You'll need to wrap the properties you want from UIEvent in its own NSCoding compliant custom type, or you can subclass UIEvent and implement NSCoding. Then you can convert your received UIEvents into the subtype. – davecom Aug 09 '17 at 15:47

0 Answers0