Unarchived object doesn't have the class descriptor of the archived object

148 Views Asked by At

I'm was writing unit tests and when I encountered a strange behaviour of NSKeyedArchiver/NSKeyedUnarchiver. The following is a failing test. Am I doing wrong?

Here is a simple project to play with: https://github.com/genesislive2007/Archiving-Headache

-(void)test {

    NSData* serializedObject = [NSKeyedArchiver archivedDataWithRootObject:[Drug new]];

    id deserializedObject = [NSKeyedUnarchiver unarchiveObjectWithData:serializedObject];

    XCTAssertTrue([deserializedObject isKindOfClass:[Drug class]]);

}

UPDATE

Some logs:

NSLog(@"Class as string: %@", NSStringFromClass([deserializedObject class]));
NSLog(@"Address of the static class: %p", [Drug class]);
NSLog(@"Address of the object class: %p", [deserializedObject class]);

Archiving Headache[1638:60b] Class as string: Drug

Archiving Headache[1638:60b] Address of the static class: 0x8bfd1d0

Archiving Headache[1638:60b] Address of the object class: 0x357c

As you see above the addreses to the class descriptiors are different.

1

There are 1 best solutions below

0
On

This has to do with the mechanisms of unarchiving, in this case it has to do with shallow copy and deep copy. When you unarchive an object and assign it to the respective return type you are creating a DEEP COPY or the archived object, a new object who's information such as its hierarchical structure and instance variables are stored in the specified folder with the given key since your using a keyed archiver, when returned will essentially make a new object/instance of the class that was archived thereby allowing you to create a deep copy and to properly restore the object in the state it was archived in as, which is the reason you are getting a new address.Program 19.10