Reputation: 3395
I have come across an odd behaviour in NSKeyedUnarchiver.
I archive a data, for this example I just use a string:
NSMutableData *myData = [ NSMutableData data ];
NSKeyedArchiver *archiver = [[ NSKeyedArchiver alloc ] initForWritingWithMutableData:myData ];
NSString *testString = [ NSString stringWithString:@"Hello World!" ];
[ archiver encodeObject:testString forKey:@"test" ];
[ archiver finishEncoding ];
and then I want to unarchive it. if I use
NSKeyedUnarchiver *unarchiver = [ NSKeyedUnarchiver unarchiveObjectWithData:myData ];
NSString *result = [ unarchiver decodeObjectForKey:@"test" ];
I get nil result, but if I use:
NSKeyedUnarchiver *unarchiver = [[ NSKeyedUnarchiver alloc ] initForReadingWithData:myData ];
NSString *result = [ unarchiver decodeObjectForKey:@"test" ];
I get my string back. Now I thought that [ NSKeyedUnarchiver unarchiveObjectWithData:myData ] is just a convenience method for [[ NSKeyedUnarchiver alloc ] initForReadingWithData:myData ], but it does not seem to behave in that way. Am I wrong.
Thanks Reza
Upvotes: 1
Views: 1348
Reputation: 112873
unarchiveObjectWithData
Apple: "Decodes and returns the object graph previously encoded by NSKeyedArchiver and stored in a given NSData object."
Which means it unarchives a complete class, not preparing to unarchive individual objects.
initForReadingWithData
Apple: "Initializes the receiver for decoding an archive previously encoded by NSKeyedArchiver.
Returns: a NSKeyedUnarchiver object initialized for for decoding data."
Which means just initializing an un-archiver ready to accept unarchive method calls.
Upvotes: 2