1

I am making a game using cocos2d-iphone and would like to make a screen with best previous scores. I have two scenes. In the MainScene I made a global variable for storing a score, that is obviously changing during the game; one mutable array and one simple array that will be a duplicate for the mutable one:

    NSInteger _scoreValue;
    NSMutableArray *_scoresMutable;
    NSArray *_scores;

In the same class, when game ends, I add new score to the mutable array, make a static duplicate and save it in NSUserDefaults:

    [_scoresMutable addObject:@(_scoreValue)];
     _scores=[NSArray arrayWithArray:_scoresMutable];
     [[NSUserDefaults standardUserDefaults] setObject:_scores forKey:@"gameScores"];

Then, in other class of scene with scores called bestscores(I don't know how is better, but it was easier for me to make just a new scene, because I am using SpriteBuilder) I import MainScene.h just in case and make a label.

At the moment I am trying to get all scores from NSUserDefaults, to sort it and to show second biggest value. But it always shows 0 (label is empty by default). So, how to make that's all right?

- (void)didLoadFromCCB {

    NSSet *numberSet = [NSSet setWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"gameScores"]];
    NSArray *sortedNumbers = [[numberSet allObjects] sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"self" ascending:NO] ]];
    NSNumber *secondHighest;

        if ([sortedNumbers count] > 1){
            secondHighest = sortedNumbers[1];
        }


[_secondBiggestLabel setString:[NSString stringWithFormat:@"%ld",(long)secondHighest]];

 }
`

EDIT : synchronize didn't help. Maybe I need to write something else to get access to NSUserDefaults from another one class?

2 Answers2

1

When you set the object you have to follow it with a call to synchronize. That will actually save it.

[[NSUserDefaults standardUserDefaults] synchronize];
Allen S
  • 1,042
  • 2
  • 9
  • 14
  • 1
    Did you debug? All you need to do after setting a user default is call synchronize. If nothing is being saved then the first thing that comes to mind is if you have allocated _scoresMutable. Debug numberSet and sortedNumbers to see if anything is there at all. – Allen S Aug 11 '14 at 00:49
0

Are you sure you've initialized that '_scoresMutable' array?

Also, if the code from the below section is ran on a separate launch than when the first section of code is ran, it's possible you're terminating the app before the defaults can write to disk. Call 'synchronize' on the NSUserDefaults instance to fix that.

Acey
  • 8,048
  • 4
  • 30
  • 46