1

我第一次尝试使用 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 的方式可能存在一些问题?

谢谢!

4

2 回答 2

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通常使用就足够了。

如果您确实使用NSKeyedArchiverand NSKeyedUnarchiver,我建议您遵循实践并为对象编写encodeWithCoder:and 。initWithCoder:

于 2011-05-09T04:46:12.200 回答
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);
    }
于 2014-05-27T12:15:41.470 回答