歸檔和解檔
Serialization
什么是Serialization?
寫(xiě)數(shù)據(jù)到本地磁盤或者進(jìn)行傳輸時(shí),需要進(jìn)行序列化,轉(zhuǎn)化成二進(jìn)制流,從而便于傳輸和存儲(chǔ)。同理,得到二進(jìn)制流后,需要進(jìn)行反序列化,還原成可以使用的數(shù)據(jù)。
需要注意的是,不同的環(huán)境,serialize和unserialize是不同的。一般同一環(huán)境中的操作才能得到正確的數(shù)據(jù)。
為什么要Serialization?
- 數(shù)據(jù)持久化
- 數(shù)據(jù)共享
- 程序之間(多進(jìn)程)
- 跨操作系統(tǒng)的數(shù)據(jù)共享
- 通過(guò)網(wǎng)絡(luò)進(jìn)行數(shù)據(jù)傳遞
- 數(shù)據(jù)存儲(chǔ)到磁盤
歸檔
寫(xiě)入到文件時(shí),可以采用下面的方法
1.writeFoFile
采用這種方法可以直接打開(kāi)查看utf-8編碼的haha.txt文件
NSString *name = @"zhangsan";
NSString *path = @"/Users/Long/wrk/haha.txt";
[name writeToFile:path atomically:YES
encoding:NSUTF8StringEncoding
error:&error];
2.archiveRootObject
NSString *name = @"zhangsan";
NSString *path = @"/Users/Long/wrk/haha.txt";
[NSKeyedArchiver archiveRootObject:name toFile:path];
打開(kāi)haha.txt, 發(fā)現(xiàn)是如下所示的內(nèi)容
bplist00‘??????
X$versionX$objectsY$archiverT$top??ü?¢??U$nullXzhangsan_??NSKeyedArchiver—?Troot?????#-27:@I[^c??
e
3.archivedDataWithRootObject
NSString *name = @"zhangsan";
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:name];
解檔
對(duì)NSData數(shù)據(jù)的解檔
[NSKeyedUnarchiver unarchiveObjectWithData:data];
自定義的類歸/解檔
需要實(shí)現(xiàn)<NSCoding>代理方法
- (id) initWithCoder: (NSCoder *)coder
- (void) encodeWithCoder: (NSCoder *)coder