I have a strange problem while working with CCSprite subclass Creature.
Lets,my object is Creature* creature;
The class Creature declaration-
@interface Creature : CCSprite <NSCoding>{
int creatureAge;
NSString *creatureName;
}
Implementation
+(id)initializeCreatureWithType:(int)type
{
Creature *creature = nil;
creature = [[[super alloc] initWithFile:[NSString stringWithFormat:@"ch%i_default.png",type]]autorelease];
return creature;
}
The problem is when i store my Creature class object ‘creature’ in NSUserDefault using-
- (void)encodeWithCoder:(NSCoder *)encoder {
[encoder encodeObject:self.creatureName forKey:@"creatureName"];
[encoder encodeInt:self.creatureAge forKey:@"creatureAge"];
}
And the decode it with-
- (id)initWithCoder:(NSCoder *)decoder {
if((self = [super init])) {
self.creatureName = [decoder decodeObjectForKey:@"creatureName"];
self.creatureAge= [decoder decodeIntForKey:@"creatureAge"];
}
Then save the creature object using-
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *myEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:creature];
[defaults setObject:myEncodedObject forKey:@"my_pet"];
And the load-
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *myEncodedObject = [defaults objectForKey:@"my_pet"];
Creature* newcreature = (Creature *)[NSKeyedUnarchiver unarchiveObjectWithData: myEncodedObject];
The problem is that when I load this i get the property value of previously stored creature, but the image that is assigned to previous creature perhaps does not copied. Because if i add the newcreature to any CCLayer it does not display any image, though it get the property value of previous creature.
What can I do now to get the newcreature with image? is it needed to add image name as a separate property???
You could simply store the type as well and then do it like this:
You might want to expose
creatureTypevia a property as well. Note that instead ofinitializeCreatureWithType:it’s “more Cocoa” to use the namecreatureWithType:.