結構體如何使用NSData封裝

來源:互聯網
上載者:User
                                                   結構體如何使用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將它顯示出來,看看對不對

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.