3 Replies
      Latest reply: Jan 8, 2017 1:39 PM by eskimo RSS
      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.

         

        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?

        • Re: How to use NSUserDefaults to store an array of custom classes in Swift?
          eskimo Apple Staff Apple Staff (6,480 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"