2011-10-28 37 views
1

我有一類名爲「防禦」與下面的自定義init方法:NSCoding使用自定義的init

// initialize the defense unit and add the sprite in the given layer 
- (id) initWithType:(DefenseType)tType andInLayer:(CCLayer *)layer { 

    NSString  *fileName; 
    fileName  = [NSString stringWithUTF8String:defenseStructuresFile[tType]]; 

    if ((self = [super initWithFile:fileName])) { 

     type    = tType; 
     maxHealth   = defenseStructuresHealth[tType]; 
     health   = maxHealth; 
     mapRef   = (SkirmishMap *)layer;   
    } 
    return self; 
} 

現在我做我的課NSCoding兼容,這需要以下2種方法:

- (id) initWithCoder:(NSCoder *)decoder 
- (void) encodeWithCoder:(NSCoder *)encoder 

當我正常分配「防」的一個實例,我的代碼如下:

Defense     *twr; 
twr     = [[Defense alloc] initWithType:type andInLayer:mapRef]; 

和磨片n個I要恢復的防禦對象我的代碼保存的實例作爲

twr     = [[decoder decodeObjectForKey:kDefense] retain]; 

但是在上面的代碼,我不能傳遞在非常需要initialize對象的「類型」和「mapref」參數,.. 。

國防類從CCSprite以來CCSprite得出不符合NSCoding,這是很好調用(self = [super initWithFile:fileName])從我initWithCoder方法。但我需要type參數來確定要傳遞到ccsprite's initWithFile的文件名。

那麼我會在這種情況下做什麼? 我應該改變我的班級設計嗎?如果是的話,怎麼樣?

什麼好的意見/建議高度讚賞... :)

回答

2

你可以做這樣的事情:

- (id)initWithCoder:(NSCoder *)decoder 
{ 
    DefenseType earlyType; 
    NSString *filename; 

    earlyType = [decoder decodeIntegerForKey:@"defense"]; 

    if (earlyType == somethingIllegal) { 
     [self release]; 
     return nil; 
    } 

    // Now do something with earlyType do determine filename 

    self = [super initWithFilename:filename]; 
    if (!self) return nil; 

    type = earlyType; 
    // Decode the rest. 

    return self; 
} 

當輸入你的方法(甚至init的),那麼self總是組。它只是一個變量(或者更確切地說:一個參數)。這就是爲什麼[self release]; return nil;即使在致電super之前也會工作。當您撥打self = [super initWithFoo:];時,您將覆蓋self。這是因爲你的超類可能會做[self release]; return nil;或分配一個具體的子類並返回它(當使用類集羣時)。所以在你調用super的初始化函數之前,覆蓋實例變量是不安全的,但是使用正常的堆棧變量(甚至是全局變量)是可以的。

+0

非常感謝你回答:)我不認爲我完全理解你的答案。但我瞭解到「自我」不是一些魔術,而只是另一個變數。並且關於我的問題,你說像「防禦型」應該被保存和恢復,而不是從所有者對象傳遞。是的,這將工作,我想.. thx再次:) – saiy2k

+0

它通過編碼和解碼防禦類內的防禦類型,如果'initWithCoder'被調用的情況下工作。對於正常分配,我使用我的舊'initWithType:andInLayer:' – saiy2k

相關問題