我有两个类:
BaseClass : NSObject
AdvanceClass : BaseClass
在 AdvanceClass 中我有一个初始化器:
-(id)initWithBaseObject:(BaseClass *)bObj
{
if(self = [super init]) {
self = (AdvanceClass*)bObj;
}
return self;
}
然后当我调用时得到 TRUE:
[myObject isKindOfClass:[BaseClass class]]
为什么?我正在将 bObj 转换为 AdvanceClass 对象。
我在这里要做的是将 BaseClass 的所有属性分配给 bObj 对象的属性。我该怎么做?
最佳答案
-(id)initWithBaseObject:(BaseClass *)bObj
{
if(self = [super init]) {
self = (AdvanceClass*)bObj; // this line of code discards the self = [super init]; and makes self a reference to a casted BaseClass object
self.property1 = bObj.property1; // this is what you need to do for each property and remove the line with the cast
}
return self;
}
关于objective-c - 如何使用基类对象定义初始化器来填充基类属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11227626/