Search code examples
iphonexcode4cocos2d-iphone

For the time being I need to save a score string for my game locally for cocos2d


How will I go about this? I can show you some of my code. but basically Im guessing that I have to save the string or something . Any tips will be very appreciated. I want this to show up in another scene.

.h file

          int _score;
          int _oldScore;
        CCLabelTTF *_scoreLabel;
         @property (nonatomic, assign) CCLabelTTF *scoreLabel;

.m file

       _score = 0;
       _oldScore = -1;
     self.scoreLabel = [CCLabelTTF labelWithString:@"" dimensions:CGSizeMake(100, 50)               alignment:UITextAlignmentRight fontName:@"Marker Felt" fontSize:32];
     _scoreLabel.position = ccp(winSize.width - _scoreLabel.contentSize.width,      _scoreLabel.contentSize.height);
     _scoreLabel.color = ccc3(255,0,0);
     [self addChild:_scoreLabel z:1];


if (_score != _oldScore) {
    _oldScore = _score;
    [_scoreLabel setString:[NSString stringWithFormat:@"score%d", _score]];



}

Solution

  • I think the easiest thing is going to be to put it in the user defaults. E.g.

    // to write
    [[NSUserDefaults standardUserDefaults] setInteger:yourScore forKey:@"score"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    // to read
    int score = [[NSUserDefaults standardUserDefaults] integerForKey:@"score"];
    

    There's a slight cost to that because of the synchronize step, so don't just do that instead of using normal internal storage, do it as well.

    The user defaults are meant to store the settings a user selects within an app. The have the slightly weird name because the assumption on the desktop way back when was that they'd be used to store the default properties that would be associated with a new document. You can store a variety of types of data to the user defaults, including NSStrings if you prefer.

    The standardUserDefaults are those just inherently provided by the OS. They're per-app so you needn't worry about naming conflicts.