< Previous PageNext Page > Hide TOC

Decoding an Archive

The easiest way to decode an archive of an object is to invoke a single class method—either unarchiveObjectWithFile: or unarchiveObjectWithData:—on the unarchiver class. These convenience methods create a temporary unarchiver object that decodes and returns a single object graph; you need do no more. NSKeyedUnarchiver requires that the object graph in the archive was encoded with one of NSKeyedArchiver’s convenience class methods, such as archiveRootObject:toFile:. The following code fragment, for example, unarchives a custom object called myMapView directly from a file.

MapView *myMapView;
NSString *archivePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"Map.archive"];
myMapView = [NSKeyedUnarchiver unarchiveObjectWithFile:archivePath];

However, if you want to customize the unarchiving process (for example, by substituting certain classes for others), you must instead create an instance of of the unarchiver class yourself, configure it as desired, and send it a decode message explicitly. NSCoder itself defines no particular method for creating a coder; this typically varies with the subclass. NSKeyedUnarchiver defines initForReadingWithData:.

Once you have the configured decoder object, to decode an object or data item, use the decodeObjectForKey: method. When finished decoding a keyed archive, you should invoke finishDecoding before releasing the unarchiver. The following sample code fragment unarchives a custom object called myMapView similar to the above code sample, but allows for customization.

MapView *myMapView;
NSData *data;
NSKeyedUnarchiver *unarchiver;
NSString *archivePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"Map.archive"];
 
data = [NSData dataWithContentsOfFile:archivePath];
unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
// Customize unarchiver here
myMapView = [unarchiver decodeObjectForKey:@"MVMapView"];
[unarchiver finishDecoding];
[unarchiver release];

It is possible to create an archive that does not contain any objects. To unarchive non-object data types, simply use the decode... method (such as decodeIntForKey: or decodeDoubleForKey:) corresponding to the original encode... method for each data item to be unarchived.



< Previous PageNext Page > Hide TOC


© 2002, 2009 Apple Inc. All Rights Reserved. (Last updated: 2009-02-04)


Did this document help you?
Yes: Tell us what works for you.
It’s good, but: Report typos, inaccuracies, and so forth.
It wasn’t helpful: Tell us what would have helped.