this question has answer here:
i tried several different method can save class in nsuserdefaults. don't know how save class override function. how can 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 doesn't 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? { { return _selectedcountryentity } set { // if newvalue != _selectedcountrytuple { _selectedcountryentity = newvalue // } } }
to store custom classes in nsuserdefaults, data type needs subclass of nsobject , should adhere nscoding protocol.
1) create custom class 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) save data use following function:
func savedata() { let data = nskeyedarchiver.archiveddatawithrootobject(custom) let defaults = nsuserdefaults.standarduserdefaults() defaults.setobject(data, forkey:"customarray" ) }
3) retrieve:
if let data = nsuserdefaults().dataforkey("customarray"), custom = nskeyedunarchiver.unarchiveobjectwithdata(data) as? [customdata] { // retrieved data item in custom { print(item) } }
note: here saving , retrieving array of trhe custom class objects.
Comments
Post a Comment