2009-11-14 77 views
0

嗨,我是新的目標C。我正在嘗試爲iPhone製作應用程序。我的視圖上有一個按鈕,並且點擊了playSound函數。這工作正常。它確實播放我想要的聲音。 現在的問題是與計時器。我希望計時器在點擊同一個按鈕時開始,計時器值將顯示在標籤中。我還不清楚NSTimer本身。我想我在這裏做錯了事。誰能幫我這個。Iphone NSTimer問題

-(IBAction)playSound { //:(int)reps 

    NSString *path = [[NSBundle mainBundle] pathForResource:@"chicken" ofType:@"wav"]; 
    NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: path]; 
    AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil]; 
    theAudio.delegate = self; 
    [theAudio play]; 

    [self startTimer]; 
} 

- (void)startTimer { 
    timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(targetMethod) userInfo:nil repeats:YES]; 
    labelA.text = [NSString stringWithFormat:@"%d", timer]; 
} 

使用上面的代碼,當我點擊按鈕,它播放聲音,然後我的應用程序關閉。

感謝 Zeeshan

回答

2

這條線:

labelA.text = [NSString stringWithFormat:@"%d", timer]; 

使得完全沒有意義的。計時器會在觸發時調用您在scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:中指定的方法作爲選擇器,因此您必須實施該方法並在那裏更新您的標籤。的startTimer第一行幾乎是正確的,但選擇必須包括冒號(因爲它表示一個參數的方法):

- (void)startTimer { 
    timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES]; 
} 

注意,我命名爲選擇timerFired:所以我們必須實現該方法。如果您希望定時器遞增計數器,你將不得不做,在這種方法中,也:

- (void)timerFired:(NSTimer *)timer { 
    static int timerCounter = 0; 
    timerCounter++; 
    labelA.text = [NSString stringWithFormat:@"%d", timerCounter]; 
} 

不要忘了計時器後無效,當你不再需要它。

+0

感謝OLE Begemann – 2009-11-14 04:33:18