2014-10-03 149 views
1

你好,我有我的計時器問題,我不明白問題出在哪裏我的問題是,在每一個milesecunds或秒我的定時器消失,並出現我不明白爲什麼:爲什麼我的計時器在每毫秒和幾秒鐘內消失?

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    self.BtnA.transform = CGAffineTransformMakeRotation(M_PI); 
    _timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(substractTime) userInfo:nil repeats:YES]; 
    [self reset:nil]; 
} 

    - (IBAction)touchBtnA:(id)sender { 
    if (enabledA) { 
     [self.BtnA setEnabled:NO]; 
     [self.BtnB setEnabled:YES]; 
     enabledA = NO; 
     enabledB = YES; 
     [self.BtnA setAlpha:0.33]; 
     [self.BtnB setAlpha:1.0]; 
    } else { 
     [self.BtnA setEnabled:YES]; 
     [self.BtnB setEnabled:NO]; 
     enabledA = YES; 
     enabledB = NO; 
     [self.BtnB setAlpha:0.33]; 
     [self.BtnA setAlpha:1.0]; 
    } 
} 

    - (IBAction)touchBtnB:(id)sender { 
    if (enabledB) { 
     [self.BtnB setEnabled:NO]; 
     [self.BtnA setEnabled:YES]; 
     enabledB = NO; 
     enabledA = YES; 
     [self.BtnB setAlpha:0.33]; 
     [self.BtnA setAlpha:1.0]; 

    } else { 
     [self.BtnB setEnabled:YES]; 
     [self.BtnA setEnabled:NO]; 
     enabledB = YES; 
     enabledA = NO; 
     [self.BtnA setAlpha:0.33]; 
     [self.BtnB setAlpha:1.0]; 
    } 
} 

    - (void)substractTime { 
    if (enabledA) { 
     _remainingTimeA--; 
     if (_remainingTimeA == 0) 
     { 
      [self pause:nil]; 
      [self.BtnA setEnabled:NO]; 
     } 
     [self updateTime:A]; 
    } 

    if (enabledB) { 
     _remainingTimeB--; 
     if (_remainingTimeB == 0) 
     { 
      [self pause:nil]; 
      [self.BtnB setEnabled:NO]; 
     } 
     [self updateTime:B]; 
    } 
} 

    - (void)updateTime: (TimerType)type { 
    NSInteger time = type == A ? _remainingTimeA : _remainingTimeB; 
    NSInteger minutes = time/600; 
    NSInteger seconds = (time/10) % 60; 
    NSInteger milliseconds = time % 10; 
    if (type == A) 
    { 
     [self.BtnA setTitle:[NSString stringWithFormat:@"%02d:%02d:%01d",minutes, seconds, milliseconds] forState:UIControlStateNormal]; 
    } 
    else 
    { 
     [self.BtnB setTitle:[NSString stringWithFormat:@"%02d:%02d:%01d",minutes, seconds, milliseconds] forState:UIControlStateNormal]; 

    } 
} 

- (IBAction)pause:(id)sender { 
enabledA = enabledB = NO; 

}

- (IBAction)reset:(id)sender { 
enabledA = enabledB = NO; 
[self.BtnA setEnabled:YES]; 
[self.BtnB setEnabled:YES]; 
_remainingTimeA = _remainingTimeB = 6000; 
[self updateTime:A]; 
[self updateTime:B]; 
[self.BtnA setAlpha:1.0]; 
[self.BtnB setAlpha:1.0]; 

}

感謝所有功能的幫助。

+0

請提供錯誤響應 – 2014-10-03 13:41:32

+5

這是一塊討厭的代碼 – 2014-10-03 13:54:36

+0

您能否提供諸如'reset:'和'pause :'。另外,問題實際上是什麼? – Chris 2014-10-03 14:20:17

回答

3

您應該知道,NSTimer不會授予您調用選擇器的重複時間間隔(在您的情況下爲1.1)的絕對準確度。換句話說,你應該計算當前和以前的選擇器調用之間的差異,這將是確切的時間間隔

+0

是的,我現在談到這個我只是把1.1看起來更好,當我的計時器開始進行更新時,在這個問題每秒都會消失並出現 – 2014-10-07 20:23:54