[英]What is the correct way to unarchive something that was archived using encodeRootObject:?
我嘗試首次使用Keyed Archiver類,但在此簡單測試(OCUnit)中,我未通過最后一個斷言:
- (void) testNSCoding
{
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:5];
[dict setObject:@"hello" forKey:@"testKey"];
NSMutableData* data = [NSMutableData data];
NSKeyedArchiver *ba = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[ba encodeRootObject:dict];
[ba finishEncoding];
STAssertTrue(data.length != 0, @"Archiver gave us nothing.");
NSKeyedUnarchiver *bua = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
id decodedEntity = [bua decodeObjectForKey:@"root"];
[bua finishDecoding];
STAssertNotNil(decodedEntity, @"Unarchiver gave us nothing.");
}
我已經確認歸檔程序正在歸檔,我假設問題在歸檔中存在。 根據《 檔案和序列化指南》,我認為我如何使用Unarchiver可能存在一些問題?
謝謝!
首先,您不應使用encodeRootObject
方法。 這是NSCoder
定義的傳統方法,用於支持過時的非鍵存檔程序,並且只能使用decodeObject:
進行解碼。 您只能使用一對encodeObjectForKey:
和decodeObjectForKey:
所以,
id decodedEntity = [bua decodeObjectForKey:@"root"];
應該
id decodedEntity = [bua decodeObjectForKey:@"testKey"];
如果要解碼字典的全部,而不是
[ba encodeRootObject:dict];
做
[ba encodeObject:dict forKey:@"root"];
順便說一句,出於簡單的目的,通常使用NSUserDefaults
就足夠了,它會自動負責創建要寫入的文件,在文件上寫東西以及在下次啟動程序時讀取它。
如果只需要對字典進行編碼, NSPropertyListSerialization
通常可以使用NSPropertyListSerialization
。
如果確實使用NSKeyedArchiver
和NSKeyedUnarchiver
,則建議您遵循該慣例,並為對象編寫encodeWithCoder:
和initWithCoder:
encodeWithCoder:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
id profileData = [defaults dataForKey:kProfileDataKey]; // or you can get it from the web
if (profileData && [profileData isKindOfClass:[NSData class]]) {
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:(NSData *)profileData];
unarchiver.requiresSecureCoding = YES; // <NSSecureCoding>
id object = [unarchiver decodeObjectOfClass:[MyClass class] forKey:NSKeyedArchiveRootObjectKey];
NSLog(@"%@", object);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.