2013-07-31 50 views
0

我對iOS開發很新,所以希望你能幫助我!我現在正在使用Xcode5-DP4,並且我的代碼工作不正常(雖然它之前工作正常)。有一個倒計時2:00(分:秒)起始通過輕敲按鈕:NSTimer不能正常工作

FirstViewController.h:

@interface FirstViewController : UIViewController { 
    IBOutlet UILabel *countdownLabel; 
    IBOutlet UIButton *countdownStart; 
    NSTimer *countdownTimer; 
    int secondsCount; 
} 

-(IBAction)alert; 
-(void)delay; 

FirstViewController.m:

UIAlertView *alert; 

-(void)delay { 
    [alert show]; 
} 


-(IBAction)alert{ 
    alert = [[UIAlertView alloc] 
      initWithTitle:@"Die Zeit ist um!" 
      message:@"Du darfst das Zähneputzen nun beenden, aber vergiss nicht, noch mehr für deine Mundhygiene zu tun." 
      delegate:self 
      cancelButtonTitle:@"OK" 
      otherButtonTitles:nil]; 

    [self performSelector:@selector(delay) withObject:nil afterDelay:120.0]; 
} 


- (IBAction)zaehneputzen:(id)sender { 

    [self setTimer]; 
} 


- (void) setTimer { 

    secondsCount = 120; 
    countdownTimer = [NSTimer scheduledTimerWithTimeInterval:(1.0) target:(self) selector:@selector(timerRun) userInfo:(nil) 
    repeats:(YES)]; 
} 

- (void) timerRun { 

    secondsCount = secondsCount-1; 
    int minutes = secondsCount/60; 
    int seconds = secondsCount - (minutes * 60); 

    NSString *timerOutput = [NSString stringWithFormat:@"%02d:%02d", minutes, seconds]; 
    countdownLabel.text = timerOutput; 

    if(secondsCount == 0){ 

     [countdownTimer invalidate]; 
     countdownTimer = nil; 

    } 
} 

存在的問題: - 計時器計數過快,不使用滿秒(標籤在0.5秒後和1.5秒後變化等等) - 計時器k eeps在計數到一個負範圍...

我希望你能幫我=)。

在此先感謝安德烈!

+0

它在xcode 4中工作嗎? –

回答

0

NSTimer有時在給定的時間間隔內不起作用。於是,我找到了一個解決方案,把下面的代碼行的NSTimer對象

[[NSRunLoop currentRunLoop] addTimer:yourtimer forMode:NSRunLoopCommonModes]; 

這可能會解決你的問題了。