结构体和NSData相互转换

假设有这么一个结构体:

      struct   MYINFO

     {

         int   a;

         long  b;

         char  c;

     };  

    struct  MYINFO    infoStruct;

    infoStruct.a = 100;

    infoStruct.b =10000;

    infoStruct.c = 'c';

     1.   将   infoStruct转换为NSData 

     NSData * msgData = [[NSData alloc]initWithBytes:&infoStruct length:sizeof(infoStruct)];

     2.  将    msgData转换为  MYINFO  对象。

      struct  MYINFO  infoStruct2;

      [msgData getBytes:&infoStruct2 length:sizeof(infoStruct2)]; 

多个结构体如何使用NSData包装

   

也许你已经非常习惯了使用NSArray和NSDictionary写成.plist来保存游戏的分数记录,非常爽吧,但是对于用惯了C的人会感觉很难受,你必须的先将他们整理成整齐的ObjC格式才行,这里将介绍一种保存任意类型的方法。可能有点小题大作,但毕竟符合一部份人的使用习惯。

 

//先来两结构,注意我们要保存的可以是 int ,float,NSString,居然还可以是UIImage

typedef struct _INT{

int t1;

int t2;

}INT_STRUCT;

typedef struct _STRING{

NSString *st1;

NSString *st2;

UIImage *image;

}STRING_STRUCT;

 

//初始化两个变量

INT_STRUCT theInt = {2,5};

STRING_STRUCT theString = {@"string1",@"string2",[UIImage imageNamed:@"icon57.png"]};

 

//将这两个变量添加到data中,他们现在是二进制

NSMutableData *theData = [NSMutableData data];

[theData appendBytes:&theInt length:sizeof(INT_STRUCT)];

[theData appendBytes:&theString length:sizeof(STRING_STRUCT)];

 

//保存到你的路径,可以不需要后缀名

[theData writeToFile:@"mySave" atomically:YES]; 


//读取

INT_STRUCT newInt;

STRING_STRUCT newString;

NSMutableData *newData = [NSData dataWithContentsOfFile:@"mySave"];


//按地址赋值,注意range的范围

[newData getBytes:&newInt range:NSMakeRange(0,sizeof(INT_STRUCT))];

[newData getBytes:&newString range:NSMakeRange(sizeof(INT_STRUCT),sizeof(INT_STRUCT)+sizeof(STRING_STRUCT))];

NSLog(@"newInt.t1===%d",newInt.t1);

NSLog(@"newString.image===%@",newString.image); 

NSLog(@"theString.image===%@",theString.image); 

OK,比较一下我们输出的newString.image和theString.image,值是一样的,你可以用UIImageView将它显示出来,看看对不对 

原文地址:https://www.cnblogs.com/chengfang/p/4093451.html