2012-06-27 35 views
0

我有兩個類:如何使用BaseClass對象定義初始化程序以填充BaseClass屬性?

BaseClass : NSObject 
AdvanceClass : BaseClass 

而且在AdvanceClass我有一個初始化:

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

    return self; 
} 

,然後當我拿到真當我打電話:

[myObject isKindOfClass:[BaseClass class]] 

爲什麼?我將bObj轉換爲AdvanceClass對象。

我想在這裏做的是從BaseClass的所有屬性與bObj對象的屬性。我怎樣才能做到這一點?

回答

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; 
    . 
    . 
    . 
} 

這是顯而易見的解決方案,我傻。

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; 
} 
+0

謝謝,但我確定有最簡單的方法分別分配每個屬性。這是令人失望的。謝謝,我會這樣做的。 – Kuba