我正在創建的遊戲中有一個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
使用'NSUserDefaults'是最簡單的方法,但是如果你不發送'synchronize'消息,你的數據就不會出現在那裏。 – Hyperbole
我在哪裏可以添加此NSUserDefaults同步方法?它看起來像什麼? – 64bitman
當完成將數據添加到默認字典以確保其持久性時,應調用'synchronize'。查看[文檔](http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/Reference/Reference.html)以獲得更清晰的解釋。 – Hyperbole