开发者

Saving Score in a Label and loading when the app opens

I'm setting 开发者_开发技巧up a "click counter" on my iOS app, so the user will know how many times he performed an action. I'm using NSUserDefaults, for I'm can't make it load when the app opens.

First I created a UILabel that stores the number and increases it each time the user click on it:

 - (IBAction) increaseScore {
self.currentScore = self.currentScore + 1;
currentScoreLabel.text = [NSString stringWithFormat: @"%ld", self.currentScore];

 // Saving:

  NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
  [defaults setObject:currentScoreLabel.text forKey: @"Score"];
  [defaults synchronize]; }

This works OK, the Label increases +1 each time I click on the button. Not sure if it is saving correctly, because when I close the app opens again, it doesn't load, the label goes back to zero:

- (void)viewDidLoad {
   [super viewDidLoad];

currentScoreLabel.text = [[NSUserDefaults standardUserDefaults] stringForKey: @"Store"];
}

Any ideas???


Looks like you got a typo there. In your increaseScore method you're setting an object for key "Score" and in your viewDidLoad you're trying to get a string for key "Store". Bummer but I always try to setup up a static NSString of they keys I'm using for this exact reason. Ex:

static NSString* kScoreKey = @"Score";

this way you call

[defaults setObject:currentScoreLabel.text forKey:kScoreKey];

and

currentScoreLabel.text = [[NSUserDefaults standardUserDefaults] stringForKey:kScoreKey];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜