0

私は2つのクラスを持っています:

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 オブジェクトのプロパティに割り当てることです。どうやってやるの?

4

2 に答える 2

2
-(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;
}
于 2012-06-27T13:45:22.363 に答える
0

BaseClassパブリックメソッドを記述し、イニシャライザから呼び出すのが最善の方法であることに気づきました。その場合、これは一度しか書くことができず、単に編集するだけです。

-(id)initWithBaseObject:(BaseClass *)bObj
{
    if(self = [super init]) {
        [self setBaseProperties:bObj];
    }

    return self;
}

そしてBaseClass.mで

-(void)setBaseProperties:(BaseClass*)bObj
{
    _prop1 = bObj.prop1;
    _prop2 = bObj.prop2;
    .
    .
    .
}

これは明らかな解決策です、ばかげています。

于 2012-06-27T14:37:28.337 に答える