我建议您为父类创建一个“复制构造函数”样式的初始化程序,并从子类初始化程序中MyClass
调用它。MyDerivedClass
[MyDerivedClass initByCopying:someMyObject plusSomeNewProperties:stuff] ->
[MyClass initByCopying:someMyObject] ->
[NSObject init] -> // alloc, etc.
这是一些伪代码:
@interface MyClass : NSObject {
int AA;
// ...
int ZZ;
}
@end
@implementation MyClass
-initByCopying:(MyClass*)other;
{
if (self = [super init])
{
self.AA=other.AA;
//...
self.ZZ=other.ZZ;
}
return self;
}
@end
@interface MyDerivedClass {
int AAA;
}
@end
@implementation MyDerivedClass
-initByCopying:(MyClass*)other withNewValue:(int)newVar;
{
if (self = [super initByCopying:(MyClass*)other])
{
self.AAA = newVar;
}
return self;
}
@end
我怀疑如果您有 1000 个成员项目,您可能需要考虑对除性能敏感的项目之外的所有项目使用属性包或 kvc,这将使您的initByCopying
日常工作更加简单。
使用复制协议实现复制构造函数可能有一个捷径,但我看不出如何使它比我上面给出的示例更容易。