objective c - Struct to NSData between Mac and iOS -
i have been working on problem while, have app running on mac, has co-ordinate data stored in struct this:
struct xyz { float x; float y; float z; }; struct xy { float x; float y; }; struct object { struct xyz *myxyz; struct xy *myxy; };
this works expected, add struct nsdata
so:
struct object aninitialteststruct; nsmutabledata *mytestdataout = [nsmutabledata datawithbytes:&aninitialteststruct length:64 freewhendone:no]; bool = [mytestdataout writetofile:[nsstring stringwithformat:@"%@/filename.dat", docsdirectory] atomically:yes];
this works expected, file , looks there data in (for reference have used pointers , malloc aninitialteststruct still don't desired result)
now on iphone, copy file project, , this:
nsstring *filepath = [[nsbundle mainbundle] pathforresource:@"filename" oftype:@"dat"]; nsdata *myvecnsdata = [[nsdata alloc] initwithcontentsoffile:filepath options:nsdatareadinguncached error:&error]; if ( error ) { nslog(@"%@", error); }
i don't correct data back. interestingly if run initwithcontents
method on mac , read file in there appears ok.
so i'm thinking there different on iphone / mac way deals filesystem.... i've tried encoding data using nskeyedarchiver
, exception stating "incomprehensible archive....."
for case of "object" structure have store "xy" , "xyz" structures separately, example in dictionary:
struct object aninitialteststruct; nsdictionary *structuredataasdictionary = [nsdictionary dictionarywithobjectsandkeys: [nsmutabledata datawithbytes:aninitialteststruct.myxy length:sizeof(xy)], @"xy key", [nsmutabledata datawithbytes:aninitialteststruct.myxyz length:sizeof(xyz)], @"xyz key", nil]; nsdata *mytestdataout = [nskeyedarchiver archiveddatawithrootobject:structuredataasdictionary]; bool = [mytestdataout writetofile:[nsstring stringwithformat:@"%@/filename.dat", docsdirectory] atomically:yes];
and decoding this:
struct object aninitialteststruct; nsstring *filepath = [[nsbundle mainbundle] pathforresource:@"filename" oftype:@"dat"]; nsdata *myvecnsdata = [[nsdata alloc] initwithcontentsoffile:filepath options:nsdatareadinguncached error:&error]; if ( error ) { nslog(@"%@", error); } // retrieving dictionary nsdata nsdictionary *structuredataasdictionary = [nskeyedunarchiver unarchiveobjectwithdata:myvecnsdata]; // allocating memory myxy , myxyz fields aninitialteststruct.myxy = (xy*)malloc(sizeof(xy)); if (aninitialteststruct.myxy == null) { // error handling } aninitialteststruct.myxyz = (xyz*)malloc(sizeof(xyz)); if (aninitialteststruct.myxyz == null) { // error handling } // filling myxy , myxyz fields read data [[structuredataasdictionary objectforkey:@"xy key"] getbytes:aninitialteststruct.myxy]; [[structuredataasdictionary objectforkey:@"xyz key"] getbytes:aninitialteststruct.myxyz];
Comments
Post a Comment