如何初始化该存档对象?

时间:2022-11-03 21:27:52

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

我做了一个符合协议的类。我已经实现了一个init方法:

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

当然,我也有一个-(void)encodeWithCoder:(NSCoder*)编码器方法实现。

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?

我还没想好如何存档这个对象。我是否需要创建一个对象的实例,然后调用-initWithCoder:并提供一个合适的NSCoder对象?

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.

我这样问的原因是我需要知道是否有可能向这个初始化方法添加另一个参数。我自己打电话的时候,我想应该没问题。尽管我必须实现带有协议正确签名的-(void)encodeWithCoder:(NSCoder*)编码器。

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

2 个解决方案

#1


0  

To encode your object, call:

要对对象进行编码,请调用:

NSData *archive = [NSKeyedArchiver archivedDataWithRootObject:myObject];

To decode it:

解码:

MyObject *myObject = [NSKeyedUnarchiver unarchiveObjectWithData:archive];

#2


0  

You can take a look at the NSArchiver class.

你可以看看NSArchiver类。

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

它是NSCoder的一个子类,将对NSData对象进行归档和反归档。

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

然后,您可以将NSData存储在一个文件或任何其他地方以重新创建对象。

#1


0  

To encode your object, call:

要对对象进行编码,请调用:

NSData *archive = [NSKeyedArchiver archivedDataWithRootObject:myObject];

To decode it:

解码:

MyObject *myObject = [NSKeyedUnarchiver unarchiveObjectWithData:archive];

#2


0  

You can take a look at the NSArchiver class.

你可以看看NSArchiver类。

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

它是NSCoder的一个子类,将对NSData对象进行归档和反归档。

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

然后,您可以将NSData存储在一个文件或任何其他地方以重新创建对象。