objective-c - 如何使用基类对象定义初始化器来填充基类属性?

标签 objective-c ios

我有两个类:

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/

相关文章:

ios - 如何保存选定的 TableView 行数据并在用户返回屏幕时显示?

iphone - TableView 组标题 View

objective-c - 什么最能描述 objective-C 和 Cocoa Bindings?

ios - 如何在 Parse 中同步 2 个异步提取?

objective-c - 如何在 Cocoa 中显示/隐藏第二个垂直分割 View ?

ios - userInteractionEnabled = NO 是什么意思,它是如何工作的?

ios - 内存泄漏: AVplayerViewController

javascript - 如果 window.open 在 IOS 中不起作用,请在同一选项卡中打开 url

javascript - 升级到 Ionic RC4 后运行应用程序时出错

iphone - 遍历 View : Objective-c 中的特定类