Table of Contents Previous Section

Using the NSCoding Protocol to Archive Custom Objects

Custom classes that can't take advantage of an EOEditingContext for archiving must take a different approach. These classes must conform to the NSCoding protocol and implement its encodeWithCoder: and initWithCoder: methods. encodeWithCoder: instructs an object to encode its instance variables to the coder provided; an object can receive this message any number of times. initWithCoder: instructs an object to initialize itself from data in the coder provided; as such, it replaces any other initialization method and is only sent once per object.

Note: Most of the Foundation classes already conform to the NSCoding protocol. This section only applies to the custom classes you write yourself.

For example, the DodgeDemo ShoppingCart class in the WebObjects examples includes the following implementations for encodeWithCoder: and initWithCoder:.

- (void)encodeWithCoder:(NSCoder *)coder {
    [coder encodeObject:carID];
    [coder encodeObject:colorID];
    [coder encodeObject:colorPicture];
    [coder encodeObject:packagesIDs];
    [coder encodeObject:downPayment];
    [coder encodeObject:leaseTerm];
}

- initWithCoder:(NSCoder *)coder {
    self = [super init];
    carID = [[coder decodeObject] retain];
    colorID = [[coder decodeObject] retain];
    colorPicture = [[coder decodeObject] retain];
    packagesIDs = [[coder decodeObject] retain];
    downPayment = [[coder decodeObject] retain];
    leaseTerm = [[coder decodeObject] retain];
    car = nil;
    return self;
}

For more information on archiving, see the NSCoding, NSCoder, NSArchiver, and NSUnarchiver class specifications in the Foundation Framework Reference.

Table of Contents Next Section