在這兩種序列化方式中,NSData都是序列化的目標(biāo)。兩種方式的不同點(diǎn)在于NSPropertyListSerialization只是針對(duì)字典/數(shù)組類型的,而NSKeyedArchiver是針對(duì)對(duì)象的。
NSCoding
NSArray, NSString, NSDictionary 提供了直接的writeToFile: atomically:
存儲(chǔ)文件是文本格式蟋恬。
NSSet, NSNumber沒(méi)有提供write接口趁冈,使用NSKeyedArchiver/NSKeyedUnarchiver 歸解檔歼争。
歸檔文件是二進(jìn)制格式, 文本編輯器無(wú)法打開箱歧。以plist做擴(kuò)展名矾飞,則用xcode可以打開查看。
自定義的類需要實(shí)現(xiàn)NSCoding協(xié)議呀邢,否則報(bào)crash:
-[class1 encodeWithCoder:]: unrecognized selector sent to instance 0x100205a40
NSPropertyListSerialization
Array,Dictionary, Boolean, Data, Date, Number, String
如果非系統(tǒng)類型洒沦,而是自定義的NSObject的model則報(bào)錯(cuò):
Property list invalid for format: 100 (property lists cannot contain objects of type 'CFType')" UserInfo={NSDebugDescription=Property list invalid for format: 100 (property lists cannot contain objects of type 'CFType')
NSPropertyListSerialization
NSData-> NSDictionary/NSArray
NSDictionary/NSArray-> NSData
NSDictionary/NSArray 直接調(diào)用writeToFile:atomically:與 NSDictionary/NSArray用NSPropertyListSerialization 轉(zhuǎn)化為NSString,再調(diào)用NSString的writeToFile:atomically:生成的文件相同价淌。
NSArray arrayWithContentsOfFile:
NSDictionary dictionaryWithContentsOfFile:與
NSPropertyListSerialization:轉(zhuǎn)化的結(jié)果相同申眼。
Info.plist不能用NSString讀取。
[NSString stringWithContentsOfFile:infoplist encoding:NSUTF8StringEncoding error:&err]
Error Domain=NSCocoaErrorDomain Code=261 "未能使用文本編碼“Unicode (UTF-8)”打開文件“Info.plist”
只能用NSDictionary dictionaryWithContentsOfFile方法蝉衣。不能用NSPropertyListSerialization