gpt4 book ai didi

objective-c - 当子类化 NSCoder 时,我是否还需要子类化集合类(即 :NSArray, NSDictionary)?

转载 作者:行者123 更新时间:2023-12-03 16:38:30 24 4
gpt4 key购买 nike

我正在探索子类化的想法NSCoder读/写专有文件格式。我开始相信这可能还需要我对 NSArrayNSDictionary 进行子类化以覆盖 encodeWithCoder: 以确保它们正确编码:

- (void)encodeWithCoder:(NSCoder *)encoder {
if ([encoder isKindOfClass:[CustomCoder class]]) {
// call [encoder encode...] as I see fit.
}else
[super encodeWithCoder:encoder];
}

我不愿意这样做,因为 NSCoder 及其相关协议(protocol) NSCoding 应该是自给自足的......要求遵循协议(protocol)的子类化似乎是糟糕的设计。我是否误解或想太多了?!?

详细说明一下:
例如,如果文件格式规定项目列表的编码方式如下:

...      // rest of file
0xA1 // marks the beginning of a list
0x0010 // amount of item in list. The list contains 16 items in this example.
... // encoded items follows

我想,要对数组进行编码,它的 encodeWithCoder: 需要如下所示:

- (void)encodeWithCoder:(NSCoder *)encoder {
[encoder encodeValueOfObjCType:@encode(short) at:&itemCount];
for ( /*for each item of the array*/ ) {
[item encodeWithCoder:encoder];
}
}

因为我忽略了 NSArray 的 encodeWithCoder: 是如何实现的,所以我想我必须重写它才能正确使用我的 NSCoder 类。

最佳答案

我不明白为什么你认为你需要子类化集合类。您的实现与默认实现有何不同?

在某些时候,NSCoder 子类的 encodeObject: 方法将被调用。在该方法中,您可以识别 NSArray 并根据您的格式要求对其进行编码。我的意思是,由您的 NSCoder 子类调用它遇到的对象的 encodeWithCoder: 或不以其他方式调用和编码它们。

关于objective-c - 当子类化 NSCoder 时,我是否还需要子类化集合类(即 :NSArray, NSDictionary)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8272686/

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