gpt4 book ai didi

ios - NSObject 不支持 encodeWithCoder?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:56:58 24 4
gpt4 key购买 nike

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

我有一个扩展 NSObject 的类,但收到下面的错误消息。这是因为 NSObject 是基类,没有什么可编码的吗?

Receiver type 'NSObject' for instance message does not declare a method with selector '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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com