I am attempting to use the Keyed Archiver classes for the first time and I’m failing the last assert in this simple test (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.");
}
I have confirmed that the archiver is archiving, I’m assuming the issue exists in the unarchiving.
According to the Archives and Serializations Guide I believe that perhaps there is some issue with how I am using the Unarchiver?
Thanks!
First, you should not use the
encodeRootObjectmethod. That’s a legacy method defined inNSCoderto support obsolete non-keyed archivers, and can only be decoded usingdecodeObject:. You only use the pair ofencodeObjectForKey:anddecodeObjectForKey:.So,
should be
If you want to decode the totality of a dictionary, instead of
do
By the way, for simple purposes it often suffices to use
NSUserDefaults, which automatically takes care of creating the file to write on, writing things on the file, and reading it when the program is launched the next time.If you just need to encode a dictionary, using
NSPropertyListSerializationusually suffices.If you do use
NSKeyedArchiverandNSKeyedUnarchiver, I recommend you to follow the practice and writeencodeWithCoder:andinitWithCoder:for an object.