Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 744191
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T08:56:59+00:00 2026-05-14T08:56:59+00:00

I’m trying to write a basic test game state singleton in cocos2d, but for

  • 0

I’m trying to write a basic test “game state” singleton in cocos2d, but for some reason upon loading the app, initWithCoder is never called. Any help would be much appreciated, thanks.

Here’s my singleton GameState.h:


#import "cocos2d.h"

@interface GameState : NSObject <NSCoding>
{
  NSInteger level, score;
  Boolean seenInstructions;
}

@property (readwrite) NSInteger level;
@property (readwrite) NSInteger score;
@property (readwrite) Boolean seenInstructions;

+(GameState *) sharedState;
+(void) loadState;
+(void) saveState;

@end

… and GameState.m:


#import "GameState.h"
#import "Constants.h"

@implementation GameState

static GameState *sharedState = nil;

@synthesize level, score, seenInstructions;

-(void)dealloc {
  [super dealloc];
}

-(id)init {
  if(!(self = [super init]))
    return nil;  
  level = 1;
  score = 0;
  seenInstructions = NO;

  return self;
}

+(void)loadState {
  @synchronized([GameState class]) {    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *saveFile = [documentsDirectory stringByAppendingPathComponent:kSaveFileName];
    Boolean saveFileExists = [[NSFileManager defaultManager] fileExistsAtPath:saveFile];

    if(!sharedState) {
      sharedState = [GameState sharedState];
    }

    if(saveFileExists == YES) {
      [sharedState release];
      sharedState = [[NSKeyedUnarchiver unarchiveObjectWithFile:saveFile] retain];
    }
    // at this point, sharedState is null, saveFileExists is 1
    if(sharedState == nil) {
      // this always occurs
      CCLOG(@"Couldn't load game state, so initialized with defaults");
      sharedState = [self sharedState];
    }
  }  
}

+(void)saveState {
  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  NSString *documentsDirectory = [paths objectAtIndex:0];
  NSString *saveFile = [documentsDirectory stringByAppendingPathComponent:kSaveFileName];
  [NSKeyedArchiver archiveRootObject:[GameState sharedState] toFile:saveFile];
}

+(GameState *)sharedState {
  @synchronized([GameState class]) {
    if(!sharedState) {
      [[GameState alloc] init];
    }
    return sharedState;
  }
  return nil;
}

+(id)alloc {
  @synchronized([GameState class]) {
    NSAssert(sharedState == nil, @"Attempted to allocate a second instance of a singleton.");
    sharedState = [super alloc];
    return sharedState;
  }
  return nil;
}

+(id)allocWithZone:(NSZone *)zone
{
  @synchronized([GameState class]) {
    if(!sharedState) {
      sharedState = [super allocWithZone:zone];
      return sharedState;
    }
  } 
  return nil;
}

...

-(void)encodeWithCoder:(NSCoder *)coder {
  [coder encodeInt:level forKey:@"level"];
  [coder encodeInt:score forKey:@"score"];
  [coder encodeBool:seenInstructions forKey:@"seenInstructions"];
}

-(id)initWithCoder:(NSCoder *)coder {
  CCLOG(@"initWithCoder called");
  self = [super init];
  if(self != nil) {
    CCLOG(@"initWithCoder self exists");
    level = [coder decodeIntForKey:@"level"];
    score = [coder decodeIntForKey:@"score"];
    seenInstructions = [coder decodeBoolForKey:@"seenInstructions"];
  }
  return self;
}
@end

… I’m saving the state on app exit, like this:


- (void)applicationWillTerminate:(UIApplication *)application {
  [GameState saveState];
  [[CCDirector sharedDirector] end];
}

… and loading the state when the app finishes loading, like this:


- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  ...
  [GameState loadState];
  ...
}

I’ve tried moving around where I call loadState too, for example in my main CCScene, but that didn’t seem to work either.

Thanks again in advance.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-14T08:56:59+00:00Added an answer on May 14, 2026 at 8:56 am

    Righteous! I think I figured it out. Plus I found a nice time-saving macro to boot: http://cocoawithlove.com/2008/11/singletons-appdelegates-and-top-level.html

    And the modified macro I’m using: http://github.com/taberrr/Objective-C-Optimized-Singleton.git (I like “sharedGameState” over “sharedInstance”)

    Hopefully this will help someone else trying to do the same thing… here’s my working NSCoder GameState singleton:

    GameState.h:

    
    #import "SynthesizeSingleton.h"
    #import "cocos2d.h"
    
    @interface GameState : NSObject <NSCoding>
    {
      NSInteger level, score;
      Boolean seenInstructions;
    }
    
    @property (readwrite) NSInteger level;
    @property (readwrite) NSInteger score;
    @property (readwrite) Boolean seenInstructions;
    
    SYNTHESIZE_SINGLETON_FOR_CLASS_HEADER(GameState);
    
    +(void)loadState;
    +(void)saveState;
    
    @end
    

    GameState.m:

    
    #import "SynthesizeSingleton.h"
    #import "GameState.h"
    #import "Constants.h"
    
    @implementation GameState
    
    @synthesize level, score, seenInstructions;
    
    SYNTHESIZE_SINGLETON_FOR_CLASS(GameState);
    
    - (id)init {
      if((self = [super init])) {
    
        self.level = 1;
        self.score = 0;
        self.seenInstructions = NO;
    
      }
      return self;
    }
    
    +(void)loadState
    {
      @synchronized([GameState class]) {
        // just in case loadState is called before GameState inits
        if(!sharedGameState)
          [GameState sharedGameState];
    
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *file = [documentsDirectory stringByAppendingPathComponent:kSaveFileName];
        Boolean saveFileExists = [[NSFileManager defaultManager] fileExistsAtPath:file];
    
        if(saveFileExists) {
          // don't need to set the result to anything here since we're just getting initwithCoder to be called.
          // if you try to overwrite sharedGameState here, an assert will be thrown.
          [NSKeyedUnarchiver unarchiveObjectWithFile:file];
        }
      }
    }
    
    +(void)saveState
    {
      @synchronized([GameState class]) {  
        GameState *state = [GameState sharedGameState];
    
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *saveFile = [documentsDirectory stringByAppendingPathComponent:kSaveFileName];
    
        [NSKeyedArchiver archiveRootObject:state toFile:saveFile];
      }
    }
    
    #pragma mark -
    #pragma mark NSCoding Protocol Methods
    
    -(void)encodeWithCoder:(NSCoder *)coder
    {
      [coder encodeInt:self.level forKey:@"level"];
      [coder encodeInt:self.score forKey:@"score"];
      [coder encodeBool:self.seenInstructions forKey:@"seenInstructions"];
    }
    
    -(id)initWithCoder:(NSCoder *)coder
    {
      self = [super init];
      if(self != nil) {
        self.level = [coder decodeIntForKey:@"level"];
        self.score = [coder decodeIntForKey:@"score"];
        self.seenInstructions = [coder decodeBoolForKey:@"seenInstructions"];
      }
      return self;
    }
    
    @end
    

    Saving:

    
    - (void)applicationWillTerminate:(UIApplication *)application {
      ...
      [GameState saveState];
      ...
    }
    

    Loading:

    
    // somewhere in your app, maybe in applicationDidFinishLaunching
    GameState *state = [GameState sharedGameState];
    NSLog(@"sharedGameState: %@", state);
    [GameState loadState];
    

    If someone sees any issues with this, PLEASE speak up. 🙂

    It appears to work fine, though.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

For some reason, after submitting a string like this Jack’s Spindle from a text
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have just tried to save a simple *.rtf file with some websites and
I want to count how many characters a certain string has in PHP, but
I used javascript for loading a picture on my website depending on which small
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am trying to render a haml file in a javascript response like so:
I have a French site that I want to parse, but am running into

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.