views:

45

answers:

2

Hey there!

I have made an class that conforms to the protocol. So I have implemented an init method like this:

- (id)initWithCoder:(NSCoder*)decoder {
 if ((self = [super init])) {
  self.someIvarObject = [decoder decodeObjectForKey:kObjectKey];
 }
 return self;
}

Of course I also have an -(void)encodeWithCoder:(NSCoder*)encoder method implemented.

I haven't figured out yet how I would archive this object now. Would I have to create an instance of my object and then just call -initWithCoder: and supply an appropriate NSCoder object?

The reason I ask is that I need to know if it's possible to add another parameter to this initialization method. When I call it by myself that should be no problem I guess. Although I would have to implement the -(void)encodeWithCoder:(NSCoder*)encoder with the correct signature for the protocol.

Maybe someone can supply a little example that quickly shows how an object is unarchived?? that would be great!

EDIT: Here's a more detailed example of what I try to do. Don't know yet if this will work with an archivable object like this...

- (id)initWithCoder:(NSCoder*)decoder somethingSpecial:(Special*)special {
 if ((self = [super init])) {
  self.someIvarObject = [decoder decodeObjectForKey:kObjectKey];
  self.somethingSpecial = special;
 }
 return self;
}

- (id)initWithCoder:(NSCoder*)decoder {
 return [self initWithCoder:decoder decimalCalculator:nil];
}
A: 

You can take a look at the NSArchiver class.

It's a subclass of NSCoder that will archive and unarchive from/to an NSData object.

You can then store the NSData on a file, or any other place to recreate the objects.

pgb
A: 

To encode your object, call:

NSData *archive = [NSKeyedArchiver archivedDataWithRootObject:myObject];

To decode it:

MyObject *myObject = [NSKeyedUnarchiver unarchiveObjectWithData:archive];
Ole Begemann
in the decoding part you posted, the variable archive would be an NSData object right?
Another Registered User
so this means that I never call -initWithCoder manually, which also means that I can't provide a parameter to my class the way I do it above, right?
Another Registered User
Yes, that's correct. If you want to write your archive directly to a file and read it directly from a file, there are also `+[NSKeyedArchiver archiveRootObject:toFile:]` and `+[NSKeyedUnarchiver unarchiveObjectWithFile:]`.
Ole Begemann
Yes, you never call `-initWithCoder:` directly. You would have to set your parameter after unarchiving.
Ole Begemann