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?