我第一次使用编码是为了将数据保存到我的应用程序之外。我一直在看的示例说要为自定义类调用[super encodeWithCoder:coder];

我有一个扩展NSObject的类,但在下面出现错误msg。这是因为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"];
}

最佳答案

没错,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;
}

关于ios - NSObject不支持encodeWithCoder吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9928839/

10-12 03:37