序列化: 將數(shù)據(jù)結(jié)構(gòu)或?qū)ο筠D(zhuǎn)換成二進(jìn)制串的過程。
反序列化:將在序列化過程中所生成的二進(jìn)制串轉(zhuǎn)換成數(shù)據(jù)結(jié)構(gòu)或者對象的過
面向?qū)ο蟮某绦蛟谶\(yùn)行的時(shí)候會(huì)創(chuàng)建一個(gè)復(fù)雜的對象圖,經(jīng)常要以二進(jìn)制的方法序列化這個(gè)對象圖,這個(gè)過程叫做Archiving. 二進(jìn)制流可以通過網(wǎng)絡(luò)或?qū)懭胛募校▉碓从谀辰滩牡囊欢卧挘?br>
本人的理解是當(dāng)你于寫數(shù)據(jù)需要本地存儲(chǔ)時(shí),即將你的數(shù)據(jù)寫到硬盤上的時(shí)候,你就必須對他進(jìn)行序列化,轉(zhuǎn)換成二進(jìn)制文件,從而便于在磁盤上的讀寫,同理在取出的時(shí)候必須將其在反序列化,這樣才能將數(shù)據(jù)讀出來,就好比加密和揭秘的過程。
在ios應(yīng)用中如果需要保存大對象數(shù)據(jù)可以采用xml文件或者屬性文件方式,但由于采用的純文本方式保密性不夠,如將保存數(shù)據(jù)封裝為自定義類的實(shí)例通過序列化的二進(jìn)制方式進(jìn)行保存,這樣安全性會(huì)有所提高。
具有序列化能力的類必須實(shí)現(xiàn)NSCoding協(xié)議的兩個(gè)函數(shù):
-(void) encodeWithCoder:(NSCoder *)encoder;
-(id) initWithCoder:(NSCoder *)decoder;
其中encodeWithCoder函數(shù)使自定義對象的各數(shù)據(jù)字段序列化,initWithCoder函數(shù)使二進(jìn)制數(shù)據(jù)文件反序列化為對象實(shí)例。例如一個(gè)網(wǎng)站的注冊用戶信息類,包含站點(diǎn)名稱siteName、站點(diǎn)地址siteAddress、注冊用戶名userName、登錄密碼password、用戶頭像logoImage。該數(shù)據(jù)類的聲明代碼:#import@interface RegUserInfo : NSObject{
NSString *siteName;
NSString *siteAddress;
NSString *userName;
UIImage *logoImage;
}
@property (nonatomic, strong) NSString *siteName, *siteAddress, *userName;
@property (nonatomic, strong) UIImage *logoImage;
@end
對數(shù)據(jù)成員序列化時(shí)需要實(shí)現(xiàn)- (void)encodeObject:(id)objv forKey:(NSString*)key,如果數(shù)據(jù)成員是基本數(shù)據(jù)類型int時(shí),需要使用
- (void)encodeInt:(int)intv forKey:(NSString*)key,encodeWithCoder的具體實(shí)現(xiàn)方式如下所示。
-(void) encodeWithCoder:(NSCoder *)encoder {
[encoder encodeObject:siteName forKey:@"siteName"];
[encoder encodeObject:siteAddress forKey:@"siteAddress"];
[encoder encodeObject:userName forKey:@"userName"];
[encoder encodeObject:logoImage forKey:@"logoImage"];
}
同樣反序列化時(shí)需要實(shí)現(xiàn)-(id) initWithCoder:(NSCoder *)decoder方法,針對每個(gè)數(shù)據(jù)成員使用- (id)decodeObjectForKey:(NSString *)key方法進(jìn)行解碼。具體代碼如下所示。
-(id) initWithCoder:(NSCoder *)decoder {
siteName = [decoder decodeObjectForKey:@"siteName"];
siteAddress = [decoder decodeObjectForKey:@"siteAddress"];
logoImage = [decoder decodeObjectForKey:@"userName"];
siteLogo = [decoder decodeObjectForKey:@"logoImage"];
return self;
}
注意:為序列化指定的key值必須保持唯一性,編碼和解碼過程中使用的key必須一致。
對userInfo對象的序列化和反序列化代碼如下所示。
/*序列化成arch.dat文件*/
[NSKeyedArchiver archiveRootObject:userInfo toFile:@"arch.dat"];
/*由文件arch.dat反序列化成RegUserInfo對象*/
RegUserInfo *newUserInfo = [NSKeyedUnarchiver unarchiveObjectWithFile: @"arch.dat"];