iOS 序列化NSCoding与NSPropertyListSerialization

在这两种序列化方式中,NSData都是序列化的目标。两种方式的不同点在于NSPropertyListSerialization只是针对字典/数组类型的,而NSKeyedArchiver是针对对象的。

NSCoding

NSArray, NSString, NSDictionary 提供了直接的writeToFile: atomically:
存储文件是文本格式。

NSSet, NSNumber没有提供write接口,使用NSKeyedArchiver/NSKeyedUnarchiver 归解档。
归档文件是二进制格式, 文本编辑器无法打开。以plist做扩展名,则用xcode可以打开查看。

自定义的类需要实现NSCoding协议,否则报crash:
-[class1 encodeWithCoder:]: unrecognized selector sent to instance 0x100205a40

image.png

NSPropertyListSerialization

Array,Dictionary, Boolean, Data, Date, Number, String

如果非系统类型,而是自定义的NSObject的model则报错:
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 直接调用writeToFile:atomically:与 NSDictionary/NSArray用NSPropertyListSerialization 转化为NSString,再调用NSString的writeToFile:atomically:生成的文件相同。

NSArray arrayWithContentsOfFile:
NSDictionary dictionaryWithContentsOfFile:与
NSPropertyListSerialization:转化的结果相同。

Info.plist不能用NSString读取。
[NSString stringWithContentsOfFile:infoplist encoding:NSUTF8StringEncoding error:&err]

Error Domain=NSCocoaErrorDomain Code=261 "未能使用文本编码“Unicode (UTF-8)”打开文件“Info.plist”

只能用NSDictionary dictionaryWithContentsOfFile方法。不能用NSPropertyListSerialization

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容