2011-08-13 3 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; 




} 

나는이 시간 동안 씨름하고 있습니다! 내가 도대체 ​​뭘 잘못하고있는 겁니까?! 참고 : 가능한 한 간단하게 설명 할 수 있습니까?

감사합니다. - 매트

+0

'NSUserDefaults'를 사용하는 것이 가장 간단한 방법이지만, '동기화'메시지를 보내지 않으면 데이터가 저장되지 않습니다. – Hyperbole

+1

이 NSUserDefaults 동기화 메서드는 어디에서 추가 할 수 있습니까? 그리고 그것은 어떻게 생겼습니까? – 64bitman

+0

'synchronize'는 데이터를 영속성을 보장하기 위해 기본 사전에 추가 한 후에 호출해야합니다. 명확한 설명을 원하면 [the docs] (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) 파일이 비어있는 경우.

또한 동기화와 함께 "디스크"에 디폴트의 쓰기를 강제하는 것을 잊지 마세요 : 당신은있는 viewDidLoad에서 또는 당신의 초기화 (또는 initWithNibName)에서 중 최고 점수를로드 할 수 있습니다

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

이 이후 방법을 부분은로드중인 뷰에 종속되지 않습니다.

viewDidLoad 메서드에서 설정 한 점수보기에서 속성을 선언 할 수 있습니다. 또는 해당 점수 클래스의 UILabel (점수가 사용하는 경우)을 점수 클래스의 속성으로 표시 할 수 있습니다.

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