結構體如何使用NSData封裝
以下文字轉載自:http://blog.csdn.net/iBright/article/details/5656164 向原作者表示感謝和敬意。
也許你已經非常習慣了使用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);
完了,比較一下我們輸出的newString.image和theString.image,值是一樣的,你可以用UIImageView將它顯示出來,看看對不對