0

I tried several different method that I can to save this class in NSUserDefaults. I don't know how to save class with override function. How can I make it?

class CountryEntity: AnyObject {
private(set) var id: UInt = 0
private(set) var name = ""

override func cityData(data: Dictionary<String, AnyObject>!) {
    id = data.uint(key: "id")
    name = data.string(key: "name")
}

}

I tried like that but it doesn't help me

  private static var _selectedCountryEntity: AnyObject? = NSUserDefaults.standardUserDefaults().objectForKey(countryNameKey) {
    didSet {
        let savedData = NSKeyedArchiver.archivedDataWithRootObject(selectedCountryEntity as! NSData)

        NSUserDefaults.standardUserDefaults().setObject(savedData, forKey: countryNameKey)
        NSUserDefaults.standardUserDefaults().synchronize()
    }
}

static var selectedCountryEntity: AnyObject? {
    get {
        return _selectedCountryEntity
    }


      set {
//            if newValue != _selectedCountryTuple {
                _selectedCountryEntity = newValue
//            }
        }
    }
Alexander Khitev
  • 6,417
  • 13
  • 59
  • 115
  • Why not just store each individual part in an array, and make serialization/deserialization methods ([take a look at this](http://stackoverflow.com/a/2315972/2767207)) – Jojodmo Jan 29 '16 at 06:44

1 Answers1

3

To store custom classes in NSUserDefaults, the data type needs to be a subclass of NSObject and should adhere to NSCoding protocol.

1) Create a custom class for your data

class CustomData: NSObject, NSCoding {
let name : String
let url : String
let desc : String

init(tuple : (String,String,String)){
    self.name = tuple.0
    self.url = tuple.1
    self.desc = tuple.2
}
func getName() -> String {
    return name
}
func getURL() -> String{
    return url
}
func getDescription() -> String {
    return desc
}
func getTuple() -> (String,String,String) {
    return (self.name,self.url,self.desc)
}

required init(coder aDecoder: NSCoder) {
    self.name = aDecoder.decodeObjectForKey("name") as! String
    self.url = aDecoder.decodeObjectForKey("url") as! String
    self.desc = aDecoder.decodeObjectForKey("desc") as! String
}

func encodeWithCoder(aCoder: NSCoder) {
    aCoder.encodeObject(self.name, forKey: "name")
    aCoder.encodeObject(self.url, forKey: "url")
    aCoder.encodeObject(self.desc, forKey: "desc")
} 
}

2) To save data use following function:

func saveData()
    {
        let data  = NSKeyedArchiver.archivedDataWithRootObject(custom)
        let defaults = NSUserDefaults.standardUserDefaults()
        defaults.setObject(data, forKey:"customArray" )
    }

3) To retrieve:

if let data = NSUserDefaults().dataForKey("customArray"),
custom = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? [CustomData] {
// Do something with retrieved data
    for item in custom {
    print(item)
    }
}

Note: Here I am saving and retrieving an array of trhe custom class objects.

Ankit Goel
  • 6,257
  • 4
  • 36
  • 48