我究竟做错了什么?我是否正确编码/解码枚举类型?
游戏设置界面:
typedef enum {
CatWhite = 0,
CatBlack = 1,
CatOrange = 2
} CatColor;
...
CatColor catColor;
...
@property CatColor catColor;
游戏设置实现:
@synthesize catColor;
...
+ (GameSettings*)GetInstance
{
if (sharedSingleton == nil) {
sharedSingleton = [[super allocWithZone:NULL] init];
sharedSingleton.catColor = CatWhite;
}
return sharedSingleton;
}
-(void)encodeWithCoder:(NSCoder *)coder {
[coder encodeInt:self.catColor forKey:@"CatColor"];
}
-(id)initWithCoder:(NSCoder *)coder {
if((self = [super init])) {
self.catColor = [coder decodeIntForKey:@"CatColor"];
}
NSLog(@"initWithCoder: %d", self.catColor); //this logs the correct int
return self;
}
AppDidFinishLaunching:
- (void)applicationDidFinishLaunching:(UIApplication *)application {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *data = [defaults objectForKey:@"GameSettings"];
GameSettings *gGameData = [NSKeyedUnarchiver unarchiveObjectWithData:data];
if(gGameData != NULL) {
GameSettings *settings = [GameSettings GetInstance];
settings.catColor = gGameData.catColor;
}else {
GameSettings *settings = [GameSettings GetInstance];
settings.catColor = CatWhite;
}
...
}
保存设置:
GameSettings* settings = [GameSettings GetInstance];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:settings];
[defaults setObject:data forKey:@"GameSettings"];
[defaults synchronize];
当我重新启动应用程序并尝试访问游戏设置时出现崩溃(程序接收信号:“EXC_BAD_ACCESS”):
GameSettings* settings = [GameSettings GetInstance];
NSLog(@"settings: %d", settings); //EXC_BAD_ACCESS
NSLog(@"catColor: %d", settings.catColor); //EXC_BAD_ACCESS
为什么重新启动后无法访问 GameSettings 单例?