NSObject不支持encodeWithCoder?

时间:2012-03-29 15:43:55

标签: ios

我第一次使用编码,以便从我的应用中保存数据。我一直在考虑的例子是为自定义类调用[super encodeWithCoder:coder];

我有一个扩展NSObject的类,但我收到错误信息如下。这是因为NSObject是基类而没有编码吗?

  

实例消息的接收者类型'NSObject'未声明具有选择器'encodeWithCoder的方法:'

- (void)encodeWithCoder:(NSCoder *) coder 
{ 
[super encodeWithCoder:coder]; //  <-------------------------ERROR

[coder encodeInt:noteIndex forKey:@"noteIndex"];
[coder encodeCGRect:cellRect forKey:@"cellRect"];
[coder encodeBool:noteOn forKey: @"noteOn"]; 
[coder encodeInt:note forKey:@"note"]; 
[coder encodeInt:velocity forKey:@"velocity"]; 
[coder encodeInt:channel forKey:@"channel"];
[coder encodeInt:releaseVelocity forKey:@"releaseVelocity"];
[coder encodeFloat:duration forKey:@"duration"];
}

1 个答案:

答案 0 :(得分:10)

没错,NSObject不符合NSCoding,所以它没有实现encodeWithCoder:。幸运的是,NSObject本身没有任何数据要编码,所以你所要做的就是:

- (void)encodeWithCoder:(NSCoder *) coder 
{ 
    [coder encodeInt:noteIndex forKey:@"noteIndex"];
    [coder encodeCGRect:cellRect forKey:@"cellRect"];
    [coder encodeBool:noteOn forKey: @"noteOn"]; 
    [coder encodeInt:note forKey:@"note"]; 
    [coder encodeInt:velocity forKey:@"velocity"]; 
    [coder encodeInt:channel forKey:@"channel"];
    [coder encodeInt:releaseVelocity forKey:@"releaseVelocity"];
    [coder encodeFloat:duration forKey:@"duration"];
}

您的initWithCoder:看起来就像:

- (id)initWithCoder:(NSCoder *)decoder {
    if (self = [super init]) {
        self.noteIndex = [decoder decodeIntForKey:@"noteIndex"];
        // and so on
    }
    return self;
}