iOS - encoding/decoding enums - crash on accessing after relaunch -
what doing wrong? encoding/decoding enum type properly?
gamesettings interface:
typedef enum { catwhite = 0, catblack = 1, catorange = 2 } catcolor; ... catcolor catcolor; ... @property catcolor catcolor;
gamesettings implementation:
@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 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; } ... }
save settings:
gamesettings* settings = [gamesettings getinstance]; nsuserdefaults *defaults = [nsuserdefaults standarduserdefaults]; nsdata *data = [nskeyedarchiver archiveddatawithrootobject:settings]; [defaults setobject:data forkey:@"gamesettings"]; [defaults synchronize];
the crash (program received signal: “exc_bad_access”) comes when re-launch app , try access game settings:
gamesettings* settings = [gamesettings getinstance]; nslog(@"settings: %d", settings); //exc_bad_access nslog(@"catcolor: %d", settings.catcolor); //exc_bad_access
why can't access gamesettings singleton after re-launch?
are sure want use applicationdidfinishlaunching there? when resurrect program, may invoking awakefromnib instead of applicationdidfinishlaunching (source: http://www.cimgf.com/2008/03/26/cocoa-tutorial-awakefromnib-vs-applicationdidfinishlaunching/ ).
Comments
Post a Comment