2

我究竟做错了什么?我是否正确编码/解码枚举类型?

游戏设置界面:

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 单例?

4

2 回答 2

0

您确定要在那里使用 applicationDidFinishLaunching 吗?当您恢复程序时,它可能会调用 awakeFromNib 而不是 applicationDidFinishLaunching(来源:http ://www.cimgf.com/2008/03/26/cocoa-tutorial-awakefromnib-vs-applicationdidfinishlaunching/ )。

于 2011-02-24T02:19:42.567 回答
0

终于想通了。GameSettings 被释放,因为 NSKeyedUnarchiver 正在自动释放它:

GameSettings *gGameData = [NSKeyedUnarchiver unarchiveObjectWithData:data];

使固定:

GameSettings *gGameData = [[NSKeyedUnarchiver unarchiveObjectWithData:data] retain];
于 2011-02-24T19:16:52.227 回答