使用CCSprite子类Creature时遇到一个奇怪的问题。
让我们的对象是生物*生物;
类生物声明 -
@interface Creature : CCSprite <NSCoding>{
int creatureAge;
NSString *creatureName;
}
实施
+(id)initializeCreatureWithType:(int)type
{
Creature *creature = nil;
creature = [[[super alloc] initWithFile:[NSString stringWithFormat:@"ch%i_default.png",type]]autorelease];
return creature;
}
问题是当我存储我的Creature类对象&#39; creature&#39;在NSUserDefault中使用 -
- (void)encodeWithCoder:(NSCoder *)encoder {
[encoder encodeObject:self.creatureName forKey:@"creatureName"];
[encoder encodeInt:self.creatureAge forKey:@"creatureAge"];
}
并用 -
解码- (id)initWithCoder:(NSCoder *)decoder {
if((self = [super init])) {
self.creatureName = [decoder decodeObjectForKey:@"creatureName"];
self.creatureAge= [decoder decodeIntForKey:@"creatureAge"];
}
然后使用 -
保存生物对象NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *myEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:creature];
[defaults setObject:myEncodedObject forKey:@"my_pet"];
负载 -
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *myEncodedObject = [defaults objectForKey:@"my_pet"];
Creature* newcreature = (Creature *)[NSKeyedUnarchiver unarchiveObjectWithData: myEncodedObject];
问题在于,当我加载它时,我获得先前存储的生物的属性值,但是分配给前一个生物的图像可能不会被复制。因为如果我将newcreature添加到任何CCLayer,它不会显示任何图像,但它会获得前一个生物的属性值。
我现在可以做些什么来获取带图像的新生物?是否需要将图像名称添加为单独的属性???
答案 0 :(得分:2)
您也可以简单地存储类型,然后按照以下方式存储:
@interface Creature : CCSprite {
int creatureType;
int creatureAge;
NSString *creatureName;
}
+ (id)creatureWithType:(int)type;
- (id)initWithCreatureType:(int)type;
@end
@implementation Creature
+ (id)creatureWithType:(int)type
{
return [[[[self class] alloc] initWithCreatureType:type] autorelease];
}
- (id)initWithCreatureType:(int)type
{
self = [super initWithFile:[NSString stringWithFormat:@"ch%i_default.png", type]];
if (!self) return nil;
creatureType = type;
return self;
}
- (id)initWithCoder:(NSCoder *)decoder {
int type = [decoder decodeIntForKey:@"creatureType"];
self = [self initWithCreatureType:type];
if (!self) return nil;
self.creatureName = [decoder decodeObjectForKey:@"creatureName"];
self.creatureAge= [decoder decodeIntForKey:@"creatureAge"];
return self;
}
- (void)encodeWithCoder:(NSCoder *)encoder
{
[encoder encodeInt:creatureType forKey:@"creatureType"];
[encoder encodeObject:self.creatureName forKey:@"creatureName"];
[encoder encodeInt:self.creatureAge forKey:@"creatureAge"];
}
@end
您可能还希望通过属性公开creatureType
。请注意,使用名称initializeCreatureWithType:
代替creatureWithType:
“更多Cocoa”。