NSKeyedUnarchiver 的行为不符合预期
我在 NSKeyedUnarchiver 中遇到了奇怪的行为。
我归档了一个数据,在这个例子中我只使用一个字符串:
NSMutableData *myData = [ NSMutableData data ];
NSKeyedArchiver *archiver = [[ NSKeyedArchiver alloc ] initForWritingWithMutableData:myData ];
NSString *testString = [ NSString stringWithString:@"Hello World!" ];
[ archiver encodeObject:testString forKey:@"test" ];
[ archiver finishEncoding ];
然后我想取消归档它。如果我使用
NSKeyedUnarchiver *unarchiver = [ NSKeyedUnarchiver unarchiveObjectWithData:myData ];
NSString *result = [ unarchiver decodeObjectForKey:@"test" ];
我会得到零结果,但如果我使用:
NSKeyedUnarchiver *unarchiver = [[ NSKeyedUnarchiver alloc ] initForReadingWithData:myData ];
NSString *result = [ unarchiver decodeObjectForKey:@"test" ];
我会取回我的字符串。现在我认为 [ NSKeyedUnarchiver unarchiveObjectWithData:myData ] 只是 [[ NSKeyedUnarchiver alloc ] initForReadingWithData:myData ] 的一种便捷方法,但它似乎并非如此。难道我错了。
谢谢 礼萨
I have come across an odd behaviour in NSKeyedUnarchiver.
I archive a data, for this example I just use a string:
NSMutableData *myData = [ NSMutableData data ];
NSKeyedArchiver *archiver = [[ NSKeyedArchiver alloc ] initForWritingWithMutableData:myData ];
NSString *testString = [ NSString stringWithString:@"Hello World!" ];
[ archiver encodeObject:testString forKey:@"test" ];
[ archiver finishEncoding ];
and then I want to unarchive it. if I use
NSKeyedUnarchiver *unarchiver = [ NSKeyedUnarchiver unarchiveObjectWithData:myData ];
NSString *result = [ unarchiver decodeObjectForKey:@"test" ];
I get nil result, but if I use:
NSKeyedUnarchiver *unarchiver = [[ NSKeyedUnarchiver alloc ] initForReadingWithData:myData ];
NSString *result = [ unarchiver decodeObjectForKey:@"test" ];
I get my string back. Now I thought that [ NSKeyedUnarchiver unarchiveObjectWithData:myData ] is just a convenience method for [[ NSKeyedUnarchiver alloc ] initForReadingWithData:myData ], but it does not seem to behave in that way. Am I wrong.
Thanks
Reza
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
unarchiveObjectWithData
Apple:“解码并返回先前由 NSKeyedArchiver 编码并存储在给定 NSData 对象中的对象图。”
这意味着它取消归档整个类,而不准备取消归档单个对象。
initForReadingWithData
Apple:“初始化接收器以解码先前由 NSKeyedArchiver 编码的存档。
返回:初始化用于解码数据的 NSKeyedUnarchiver 对象。”
这意味着只需初始化一个准备好接受取消归档方法调用的取消归档器。
unarchiveObjectWithData
Apple: "Decodes and returns the object graph previously encoded by NSKeyedArchiver and stored in a given NSData object."
Which means it unarchives a complete class, not preparing to unarchive individual objects.
initForReadingWithData
Apple: "Initializes the receiver for decoding an archive previously encoded by NSKeyedArchiver.
Returns: a NSKeyedUnarchiver object initialized for for decoding data."
Which means just initializing an un-archiver ready to accept unarchive method calls.