我有一類名爲「防禦」與下面的自定義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的文件名。
那麼我會在這種情況下做什麼? 我應該改變我的班級設計嗎?如果是的話,怎麼樣?
什麼好的意見/建議高度讚賞... :)
非常感謝你回答:)我不認爲我完全理解你的答案。但我瞭解到「自我」不是一些魔術,而只是另一個變數。並且關於我的問題,你說像「防禦型」應該被保存和恢復,而不是從所有者對象傳遞。是的,這將工作,我想.. thx再次:) – saiy2k
它通過編碼和解碼防禦類內的防禦類型,如果'initWithCoder'被調用的情況下工作。對於正常分配,我使用我的舊'initWithType:andInLayer:' – saiy2k