Crazycriss
Crazycriss

Reputation: 315

Saving and Retrieving Score String Cocos2d 3.0

How would I be able to save my score string then recall it? I've seen a lot of answers for this question but they have all been on an earlier version of Cocos2d, I've tried to implement them but no luck :(

This is the code that displays the score at the moment

score=0;
scorelabel = [CCLabelTTF labelWithString:[NSString stringWithFormat:@"score: %d",score] fontName:@"a2203.ttf" fontSize:21.0f];
scorelabel.positionType = CCPositionTypeNormalized;
scorelabel.color = [CCColor blackColor];
scorelabel.position = ccp(0.85f, 0.95f); // Top Right of screen
[self addChild:scorelabel];

Thank you for any advice :D

New code

- (id)init
{
// Apple recommend assigning self with supers return value
self = [super init];
if (!self) return(nil);

int savedScore  = [[NSUserDefaults standardUserDefaults] integerForKey:@"score_key"];

CCLabelTTF *ahighScore = [CCLabelTTF labelWithString:[NSUserDefaults stringWithFormat:@"score: %d",score_key] fontName:@"a2203.ttf" fontSize:23.0f];
ahighScore.positionType = CCPositionTypeNormalized;
ahighScore.color = [CCColor blackColor];
ahighScore.position = ccp(0.5f, 0.90f);
[self addChild:ahighScore];

return self;
}

Upvotes: 0

Views: 236

Answers (1)

Abhineet Prasad
Abhineet Prasad

Reputation: 1271

As suggested by LearnCocos2D, save score to NSUserDefaults by

[[NSUserDefaults standardUserDefaults] setInteger:score forKey:@"score_key"];
[[NSUserDefaults standardUserDefaults] synchronize];

You can retrieve the score from NSUserDefaults by

int savedScore  = [[NSUserDefaults standardUserDefaults] integerForKey:@"score_key"];

Upvotes: 1

Related Questions