ios - Writing NSDictionary with custom objects to file -
this question has answer here:
i have nsdictionary
array of custom objects, called maclass
es. try writing dict file, simple method:
- (void)writedicttofilewithcontent:(nsdictionary *)contentdict { nsarray *paths = nssearchpathfordirectoriesindomains(nsdocumentdirectory, nsuserdomainmask, yes); nsstring *documentsdirectory = [paths objectatindex:0]; nsstring *filepath = [documentsdirectory stringbyappendingpathcomponent:@"/userdata.txt"]; [contentdict writetofile:filepath atomically:yes]; }
and read using
- (nsdictionary *)readfromdict { nsarray *paths = nssearchpathfordirectoriesindomains(nsdocumentdirectory, nsuserdomainmask, yes); nsstring *documentsdirectory = [paths objectatindex:0]; nsstring *filepath = [documentsdirectory stringbyappendingpathcomponent:@"/userdata.txt"]; nsdictionary *contentdict = [nsdictionary dictionarywithcontentsoffile:filepath]; return contentdict; }
the array of objects i'm trying write custom nsobject, structured kinda this:
@interface maassignment : nsobject @property (nonatomic, strong) nsdate *date; @property (nonatomic, strong) nsstring *assignmentname; @property (nonatomic, strong) nsnumber *totalpoints; @property (nonatomic, strong) nsnumber *recievedpoints; @property (nonatomic, strong) nsnumber *classaverage; @property (nonatomic, strong) nsnumber *extracredit; @property (nonatomic, strong) nsnumber *notgraded;
which represents class.
i earlier using arrays of nsstrings , nsnumbers, , read , write fine. when switched the maclass object returned empty dict when tried read.
this why: iphone - writing nsmutabledictionary file
what should write dict instead?
you need serialize custom objects, 1 way following, in custom class write following 2 methods encoding/decoding each property want persist, not sure if writetofile use this, know can create nsdata object , write file following method
//archive dictionary , serializable objects nsdata nsdata *serializeddata= [nskeyedarchiver archiveddatawithrootobject:mydict]; //unarchive nsdata *mydata=[nsdata datawithcontentsoffile:appfile]; nsmutabledictionary* mydict= (nsmutabledictionary*)[nskeyedunarchiver unarchiveobjectwithdata:mydata];
here 2 methods need in custom objects:
- (void)encodewithcoder:(nscoder *)coder { [coder encodeint:self.propone forkey:@"propone"]; [coder encodeobject:self.proptwo forkey:@"proptwo"]; ... } // decode object archive - (id)initwithcoder:(nscoder *)coder { self = [super init]; self.propone=[coder decodeintegerforkey:@"propone"]; self.proptwo=[coder decodeobjectforkey:@"proptwo"]; .. return self; }
hope helps
Comments
Post a Comment