2011-05-09 22 views
1

我試圖使用鍵控歸檔類的第一次,我沒有最後斷言在這個簡單的測試(的OCUnit):解開使用encodeRootObject存檔的內容的正確方法是什麼?

- (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."); 
} 

我已經證實,歸檔的歸檔,我假設問題存在於非存檔中。 根據Archives and Serializations Guide我相信或許我在使用Unarchiver的過程中遇到了一些問題?

謝謝!

回答

1

首先,你不應該使用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通常就足夠了。

如果您確實使用NSKeyedArchiverNSKeyedUnarchiver,我建議您按照練習編寫encodeWithCoder:initWithCoder:作爲對象。

+0

對不起,沒有通過,我不想要字符串「你好」,我試圖讓字典。要回答你的問題,上面的鏈接頁面的底部說:如果你想定製先前使用archiveRootObject:toFile創建的檔案的解除歸檔過程,你可以使用decodeObjectForKey:和鍵「root」來標識存檔。 – 2011-05-09 04:49:28

+0

感謝NSUserDefaults上的提示。這個測試適用於我正在寫的一個更復雜的酸洗子系統。 NSUserDefaults是不夠的。 – 2011-05-09 04:50:51

+0

好吧,但是你沒有使用'archiveRootObject:toFile:',是嗎? – Yuji 2011-05-09 04:58:02

0
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); 
    } 
相關問題