目标C - 如何使用initWithCoder方法?

时间:2010-10-15 15:41:55

标签: objective-c cocoa-touch nscoder

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

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

如何实例化此类的对象? 这是NSCoder的内容是什么?我该如何创建它?

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

2 个答案:

答案 0 :(得分:40)

您还需要按如下方式定义以下方法:

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

答案 1 :(得分:16)

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

这是一种在流(如文件,套接字)上编写对象并能够在以后或在不同的地方检索它们的方法。

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