ios - Why `NSUserDefaults` not allowed to store objects of Custom Classes? -
i've seen nsuserdefaults not allow objects other array, dictionary, string, nsdata, nsnumber, bool, nsdate. but
- why not allowed store other objects?
 - what if need store properties single object? if using dictionary, i've write keys somewhere i've used store value. so, other alternatives.
 - what problems arise if 
appleallows other objects store. - what if use 
coredatainsteadnsuserdefaults. knownsuserdefaultsglobally available. - what best way make value available globally after relaunched app if terminated?
 
as suggested @hoa, forgot mention nscoding option also
- what if have many properties in custom class, need encode , decode of them using 
nscodingmethods? 
you can save object plist file long compliant nscoding protocol.
you can use code similar this:
+(id) readobjectfromfile:(nsstring*) sfilename {     return [nskeyedunarchiver unarchiveobjectwithfile:sfilename]; }   +(bool) saveobject:(id <nscoding>) anobject tofile:(nsstring*) sfilename {     nsdata * data = [nskeyedarchiver archiveddatawithrootobject:anobject];     nserror * error;     [data writetofile:sfilename options:nsdatawritingatomic error:&error];     if (error)         {             nslog(@"save cats data error: %@", error.description);             return no;         }     return yes; }   swift version:
func readobjectfromfile(sfilename: string) -> anyobject {    return nskeyedunarchiver.unarchiveobjectwithfile(sfilename) }  func saveobject(anobject: anyobject, tofile sfilename: string) -> bool {     var data: nsdata = nskeyedarchiver.archiveddatawithrootobject(anobject)     var error: nserror     data.writetofile(sfilename, options: nsdatawritingatomic, error: error)     if error != nil {         print("save cats data error: \(error.description)")         return false     }     return true }   to learn more nscoding protocol can read: https://developer.apple.com/library/mac/documentation/cocoa/reference/foundation/protocols/nscoding_protocol/
Comments
Post a Comment