4 Replies
      Latest reply on Sep 16, 2018 12:10 PM by Adalex
      danielbramhall Level 1 Level 1 (0 points)

        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.


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


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

        • Re: How to use NSUserDefaults to store an array of custom classes in Swift?
          eskimo Apple Staff Apple Staff (13,925 points)

          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"