iOS - 编码/解码枚举 - 重新启动后访问时崩溃

时间:2011-02-24 01:20:20

标签: ios encoding nsuserdefaults nskeyedarchiver

我做错了什么?我能正确编码/解码枚举类型吗?

GameSettings界面:

typedef enum {
    CatWhite = 0,
    CatBlack = 1,
    CatOrange = 2
} CatColor;

...
CatColor catColor;
...
@property CatColor catColor;

GameSettings实施:

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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

终于弄明白了。 GameSettings被取消分配,因为NSKeyedUnarchiver正在自动释放它:

GameSettings *gGameData = [NSKeyedUnarchiver unarchiveObjectWithData:data];

修正:

GameSettings *gGameData = [[NSKeyedUnarchiver unarchiveObjectWithData:data] retain];