2011-08-13 81 views
0

我正在創建的遊戲中有一個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

使用'NSUserDefaults'是最簡單的方法,但是如果你不發送'synchronize'消息,你的數據就不會出現在那裏。 – Hyperbole

+1

我在哪裏可以添加此NSUserDefaults同步方法?它看起來像什麼? – 64bitman

+0

當完成將數據添加到默認字典以確保其持久性時,應調用'synchronize'。查看[文檔](http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/Reference/Reference.html)以獲得更清晰的解釋。 – Hyperbole

回答

2

讀它:

int highscore = [[NSUserDefaults standardUserDefaults] integerForKey: @"highScore"]; 

這將最有可能是int的默認值(即0)時,文件爲空。

也不要忘記給力您的默認值的寫爲「盤」與其它設備同步:

-(void)saveScore { 
    NSUSerDefaults *defaults = [NSUserDefaults standardUserDefaults]; 
    [defaults setInteger:score forKey:@"highScore"]; 
    [defaults synchronize]; 
} 

您可以加載高分無論是在viewDidLoad中,甚至在你的init(或initWithNibName),因爲這種方法部分不依賴於你的視圖被加載。

您可以在viewDidLoad方法中設置的Scores視圖中聲明一個屬性。或者,您可以將該分數類的UILabel(如果這是您使用的)作爲分數類的屬性公開。

- (void)viewDidLoad: 
{ 
... 
self.scoresView.textLabel.text = [NSString stringWithFormat:@"%d", highScore]; 
... 
}