【发布时间】:2012-08-23 16:15:59
【问题描述】:
我正在尝试为 NSCoding 协议创建一个通用实现。 代码将被包裹在一个宏中,该宏将实现 NSCoding。 为了实现协议,我们需要两个函数:
-(void)encodeWithCoder:(NSCoder*)coder;
-(id)initWithCoder:(NSCoder*)coder;
initWithCoder 函数的通用实现是:
-(id)initWithCoder:(NSCoder*)coder {
if ([super conformsToProtocol:@protocol(NSCoding)])
self = [super initWithCoder:coder];
else {
self = [super init];
}
if (!self) return self;
self = [MyGenericCoder initWithCoder:coder forObject:self withClass:[__clazz class]];
return self;
}
有问题的行是self = [super initWithCoder:coder];,它不会编译,因为当我们在其super 不实现NSCoding 的类中使用时,super 不会响应initWithCoder:。将 super 转换为 NSObject<NSCoding>* 不适用于 LLVM 编译器。
[super performSelector:(initWithCoder:) withObject:coder] 也不起作用,因为 super == self,这将导致无限循环。
如何调用[super initWithCoder:coder] 以触发超类中的函数并且不会生成编译警告/错误?
【问题讨论】:
-
“它不会编译”你大概是指你收到警告?除非您将相关的编译器选项设置为将警告视为错误,否则我认为它至少应该编译。如果你只是将 super 转换为
(id),LLVM 会怎么想?
标签: objective-c inheritance macros nscoding overriding