< Previous PageNext Page > Hide TOC

Creating an Archive

The easiest way to create an archive of an object graph is to invoke a single class method—either archiveRootObject:toFile: or archivedDataWithRootObject:—on the archiver class. These convenience methods create a temporary archiver object that encodes a single object graph; you need do no more. The following code fragment, for example, archives a custom object called myMapView directly to a file.

MapView *myMapView;   // Assume this exists
NSString *archivePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"Map.archive"];
result = [NSKeyedArchiver archiveRootObject:myMapView
                        toFile:archivePath];

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

Once you have the configured coder object, to encode an object or data item, use any encode method for an NSKeyedArchiver coder. When finished encoding a keyed archive, you must invoke finishEncoding before accessing the archive data. The following sample code fragment archives a custom object called myMapView similar to the above code, but allows for customization.

MapView *myMapView;   // Assume this exists
NSMutableData *data;
NSString *archivePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"Map.archive"];
NSKeyedArchiver *archiver;
BOOL result;
 
data = [NSMutableData data];
archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
// Customize archiver here
[archiver encodeObject:myMapView forKey:@"MVMapView"];
[archiver finishEncoding];
result = [data writeToFile:@archivePath atomically:YES];
[archiver release];

It is possible to create an archive that does not contain any objects. To archive other data types, invoke one of the type-specific methods, such as encodeInteger:forKey: or encodeDouble:forKey: directly for each data item to be archived, instead of using encodeRootObject:.

Legacy Note:  Creating a non-keyed archive (using NSArchiver) by encoding item by item should not be used to archive objects. Use encodeRootObject: instead, to avoid the problems mentioned in “Root Object” and to simplify unarchiving. A keyed archive can have multiple objects encoded with different keys at the root, or top, of the archive.



< 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.