I have a class named “Defense” with custom init method as below:
// 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;
}
now i am making my class NSCoding compatible, which requires the following 2 methods:
- (id) initWithCoder:(NSCoder *)decoder
- (void) encodeWithCoder:(NSCoder *)encoder
When I normally allocate an instance of “Defense”, I code as follows:
Defense *twr;
twr = [[Defense alloc] initWithType:type andInLayer:mapRef];
and when I want to restore a saved instance of Defense object I code as
twr = [[decoder decodeObjectForKey:kDefense] retain];
But in the above code I cant pass the “type” and “mapref” parameters, which are very much required to initialize the object…
The Defense class derives from CCSprite and since CCSprite doesn’t conform to NSCoding, it is fine to call (self = [super initWithFile:fileName]) from my initWithCoder method. But I require the type parameter to determine the filename to be passed to ccsprite's initWithFile.
So what would I do in this situation?
Should I change my class design? if yes, how?
Any good ideas/suggestions are highly appreciated… 🙂
You can do something like this:
When your methods are entered (even
init‘s) thenselfis always set. And it’s just a variable (or to be more precise: an argument). This is why[self release]; return nil;will work even before callingsuper. When you callself = [super initWithFoo:];you’re overwritingself. This is done because your super class might do[self release]; return nil;or allocate a concrete subclass and return that instead (when using a class cluster). So before you call super’s initializer, it’s not safe to overwrite instance variables, but it’s OK to use normal stack variables (or even global variables).