0

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.

  • What is the class of deserializedObject, you can log it out. – KudoCC Aug 09 '14 at 11:24
  • The class descriptiors are pointing to different objects. I guess that the problem is here. But...How should I rewrite this test? – genesislive2007 Aug 09 '14 at 11:41
  • you may want to check how did you decode in Drug class. Or try to print out the class name and verify. NSString *className = NSStringFromClass([yourObject class]); – dumduke Aug 11 '14 at 16:39

1 Answers1

0

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

Community
  • 1
  • 1