我正在创建的游戏有一个highScore整数变量,在玩家输掉时会被分配。我正在使用NSUsersDefaults类来保存我的高分。这是我正在使用的代码:
-(void)saveScore {
[[NSUserDefaults standardUserDefaults] setInteger:score forKey:@"highScore"];
[defaults setInteger:score forKey:@"highScore"];
[defaults synchronize];
NSLog(@"High Score: %i ", highScore);
}
-(IBAction)buttonReleased:(id)sender {
[stopWatchTimer invalidate];
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
NSString *label0 = @"Hold to Start";
[labelText setText:label0];
if (score > 0) {
score--;
}
else {
score = 0;
NSLog(@"Changed score to 0");
}
if (score > highScore) {
[self saveScore];
NSString *scoreMessage =[[NSString alloc] initWithFormat:@"Congrats! You have a new High Score! Click Share High Score to share your score of: %i",score];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"High Score!" message:(NSString *)scoreMessage delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alert show];
[alert release];
score = 0;
}
else {
NSString *scoreMessage =[[NSString alloc] initWithFormat:@"Game Over! Your score was: %i",score];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"GAME OVER!" message:(NSString *)scoreMessage delegate:nil cancelButtonTitle:@"Try Again" otherButtonTitles: nil];
[alert show];
[alert release];
score = 0;
}
- (void)viewDidLoad
{
[super viewDidLoad];
int highscore = [[NSUserDefaults standardUserDefaults] integerForKey: @"highScore"];
[stopWatchTimer invalidate];
stopWatchTimer=nil;
}
我一直在为这个小时摔跤!我究竟做错了什么?!注意:您能否尽可能简单地解释一下。
谢谢! -Matt
答案 0 :(得分:2)
读它:
int highscore = [[NSUserDefaults standardUserDefaults] integerForKey: @"highScore"];
当文件为空时,它很可能是int的默认值(即0)。
另外,不要忘记使用synchronize强制将默认值写入“disk”:
-(void)saveScore {
NSUSerDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setInteger:score forKey:@"highScore"];
[defaults synchronize];
}
您可以在viewDidLoad或甚至init(或initWithNibName)方法中加载高分,因为此部分不依赖于您正在加载的视图。
您可以在scores视图中声明您在viewDidLoad方法中设置的属性。或者,您可以将该分数类的UILabel(如果这是您使用的)暴露为您的分数类的属性。
- (void)viewDidLoad:
{
...
self.scoresView.textLabel.text = [NSString stringWithFormat:@"%d", highScore];
...
}
答案 1 :(得分:1)
有一个非常简单的高分管理系统,我写它甚至有在线支持。你可以找到它https://github.com/faizanaziz/HighScore