开发者

How to initialize this archived object?

开发者 https://www.devze.com 2022-12-10 01:11 出处:网络
I have made an class that conforms to theprotocol. So I have implemented an init method like this: - (id)initWithCoder:(NSCoder*)decoder {

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 implem开发者_运维百科ented.

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];
}


To encode your object, call:

NSData *archive = [NSKeyedArchiver archivedDataWithRootObject:myObject];

To decode it:

MyObject *myObject = [NSKeyedUnarchiver unarchiveObjectWithData:archive];


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号