Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Richard Rodriguez
2,687 PointsSpriteKit :Could someone help with saving a score using NSUserDefaluts ?
This is what I have so far and it displays the score on the HUD, but how do I save that score and where do I write the code??
SKLabelNode *scoreLabel = [SKLabelNode labelNodeWithFontNamed:@"Futura-CondensedExtraBold"];
scoreLabel.name = @"Score";
scoreLabel.text =@"0";
scoreLabel.fontSize = 24;
scoreLabel.horizontalAlignmentMode = SKLabelHorizontalAlignmentModeRight;
scoreLabel.position = CGPointMake(frame.size.width-20, -10);
[hud addChild:scoreLabel];
return hud;
}
-(void) addPoints: (NSInteger)points {
self.score += points;
SKLabelNode *scoreLabel = (SKLabelNode*) [self childNodeWithName:@"Score"];
scoreLabel.text = [NSString stringWithFormat:@"%ld", (long)self.score];
1 Answer

Stone Preston
42,016 Pointsto save the score using NSUserDefaults:
// Store the score
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setInteger:self.score: forKey:@"score"];
you would put this code wherever you want to save the score,
to retrieve the score
// Get the score
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSInteger *retrievedScore = [defaults integerForKey:@"score"];
you would put this code whereever you want to retrieve the score
saving the score itself to the defaults really isnt necessary. what you could do is save a high score to the defaults whenever the game is over
Richard Rodriguez
2,687 PointsRichard Rodriguez
2,687 PointsSo if i have a score label in the TitleScene, how do I make it display that value ?
Stone Preston
42,016 PointsStone Preston
42,016 Pointsyou grab the value from defaults and set the text of the label to that value:
keep in mind you may need to add some checks to make sure the score actually exists in the defaults before you set the text