1

Using this: https://github.com/jonasman/TeslaSwift Class: ViewController

I am trying to store a value vehicle in NSUserDefault like this:

var vehicle: Vehicle!
UserDefaults.standard.set(vehicle, forKey: "selectedCar")

But I get the following error:

Attempt to insert non-property list object TeslaSwift.Vehicle for key selectedCar' terminating with uncaught exception of type NSException

Any ideas on how to store it?

Erik Auranaune
  • 1,384
  • 1
  • 12
  • 27

1 Answers1

0

Reading the doc of UserDefaults:

The UserDefaults class provides convenience methods for accessing common types such as floats, doubles, integers, Boolean values, and URLs. These methods are described in Setting Default Values.
A default object must be a property list—that is, an instance of (or for collections, a combination of instances of) NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary. If you want to store any other type of object, you should typically archive it to create an instance of NSData.

The old way (more Objective-C way), is to conforms to NSCoding. That's a way to transforming from/to ClassA <-> (NS)Data. The "new way", is to use Codable, which is more Swift, but has some differences from previous solution (it's more "universal", but could have extra steps needed for more "complexes" stuffs).

Since Vehicle is Codable, use a Encoder (usually, JSONEncoder) to encode it into Data, and then save it into UserDefaults, and a Decoder (usually JSONDecoder) to retrieve it. But it could be also PlistEncoder/PlistDecoder.

Larme
  • 24,190
  • 6
  • 51
  • 81
  • I tried doing it like this: `let pieceData = try? NSKeyedArchiver.archivedData(withRootObject: vehicle, requiringSecureCoding: false)`, but I get error message: `NSForwarding: warning: object 0x600000ce4540 of class 'TeslaSwift.Vehicle' does not implement methodSignatureForSelector` – Erik Auranaune Jul 17 '21 at 20:46
  • Don't, It's `Codable`, don't use NSKeyedArchiver which is for `NSCoding`, use JSONEncoder ! – Larme Jul 17 '21 at 20:49