How to use NSUserDefaults to store an array of custom classes in Swift?

I have a custom class called

Person
that stores various attributes about someone when they enter information.
class Person {
     var name: String? 
     var age: String? 
     var html_url: String? init(json: NSDictionary) 

     {
          self.name = json["name"] as? String 
                    self.age = json["age"] as? String 
                    self.html_url = json["html_url"] as? String /
          } 
}

Once the dictionary is created, it is then placed into an array. I am having problems saving the array into

NSUserDefaults
when a button is tapped.


personArray.append(newPerson)
NSUserDefaults.standardUserDefaults().setObject(personArray, forKey: "personArray") NSUserDefaults.standardUserDefaults().synchronize()

/discussion/http:

Would anyone be able to help me actually save an array of custom objects (custom dictionaries) via NSUserDefaults?

Replies

NSUserDefaults won’t save custom classes. The standard way of getting around this is to implement NSCoding in your class, then create a keyed archive from your objects and save that data in NSUserDefaults.

However, I question whether NSUserDefaults is the right option here. NSUserDefaults is intended for saving simple preferences, not for saving user data (which, btw, is why it doesn’t support saving custom objects). You might be better off saving your data via custom code. There’s lots of options in this space, including:

  • create a keyed archive and save that in a file

  • implement your own serialisation scheme

  • Core Data

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

Hello, is there a way to save an array of GMSPolygon into UserDefaults?

Thanks

GMSPolygon is not an Apple thing. If it’s your own thing then you should post some details about it and we’ll try and help out from there. If it’s part of some third-party library, you might want to follow up via the support channel associated with that library.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

I have a similar problem where I am trying to store a dictionary of [Int : Place(My custom structure)]. You said you can create a keyed archive of this and store it that way? How can I do that so I can store a value of [Int : Place] and get a value of [Int : Place] when I try to read it from User Defaults?


I've tried:

let data = NSKeyedArchiver.archivedData(withRootObject: withLocations)
        UserDefaults.standard.set(data, forKey: "wanderLocations")


But my app crashes at this with the error "-[_SwiftValue encodeWithCoder:]: unrecognized selector sent to instance 0x1c0308a60"