48

我的类有以下方法,它打算加载一个 nib 文件并实例化对象:

- (id)initWithCoder:(NSCoder*)aDecoder 
{
    if(self = [super initWithCoder:aDecoder]) {
        // Do something
    }
    return self;
}

如何实例化此类的对象?这是什么NSCoder?我怎样才能创建它?

    MyClass *class = [[MyClass alloc] initWithCoder:aCoder];
4

2 回答 2

41

您还需要定义如下方法:

- (void)encodeWithCoder:(NSCoder *)enCoder {
    [super encodeWithCoder:enCoder];

    [enCoder encodeObject:instanceVariable forKey:INSTANCEVARIABLE_KEY];

    // Similarly for the other instance variables.
    ....
}

并在 initWithCoder 方法中初始化如下:

- (id)initWithCoder:(NSCoder *)aDecoder {

   if(self = [super initWithCoder:aDecoder]) {
       self.instanceVariable = [aDecoder decodeObjectForKey:INSTANCEVARIABLE_KEY];

       // similarly for other instance variables
       ....
   }

   return self;
}

您可以以标准方式初始化对象,即

CustomObject *customObject = [[CustomObject alloc] init];
于 2010-10-15T15:57:50.737 回答
18

该类NSCoder用于归档/取消归档(编组/解组,序列化/反序列化)对象。

这是一种在流(如文件、套接字)上写入对象并能够稍后或在不同位置检索它们的方法。

我建议你阅读http://developer.apple.com/library/mac/#documentation/cocoa/conceptual/Archiving/Archiving.html

于 2010-10-15T15:47:04.717 回答