所以我有一个带有计时器的视图控制器。它有一个按钮。当视图第一次加载时,按钮应该说“开始”。
点击它时,“开始”->“暂停”。
再次点击,“暂停”->“恢复”。
再次点击,“恢复”->“暂停”。
由于我希望计时器准确,因此我将其从主线程中分离出来(我认为我选择了正确的方法,我希望得到一些澄清)。但似乎将它与线程分离实际上调用了该方法......这使得按钮以“暂停”而不是开始。我该如何解决?
顺便说一下,testTask.showButtonValue 的默认值(加载)是 1。
- (void)viewDidLoad {
[super viewDidLoad];
[NSThread detachNewThreadSelector:@selector(startTimer:) toTarget:self withObject:nil];
if (testTask.showButtonValue == 1) {
[startButton setTitle:@"Start" forState:UIControlStateNormal];
} else if (testTask.showButtonValue == 2) {
[startButton setTitle:@"Pause" forState:UIControlStateNormal];
} else if (testTask.showButtonValue == 3){
[startButton setTitle:@"Resume" forState:UIControlStateNormal];
}
}
-(IBAction)startTimer:(id)sender{
if (testTask.showButtonValue == 1) {
[startButton setTitle:@"Pause" forState:UIControlStateNormal];
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
testTask.showButtonValue = 2;
} else if (testTask.showButtonValue == 2) {
[startButton setTitle:@"Resume" forState:UIControlStateNormal];
[timer invalidate];
timer = nil;
testTask.showButtonValue = 3;
} else if (testTask.showButtonValue == 3){
[startButton setTitle:@"Pause" forState:UIControlStateNormal];
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
testTask.showButtonValue = 2;
}
}
-(void)timerAction:(NSTimer *)t
{
if(testTask.timeInterval == 0)
{
if (self.timer)
{
[self timerExpired];
[self.timer invalidate];
self.timer = nil;
}
}
else
{
testTask.timeInterval--;
}
NSUInteger seconds = (NSUInteger)round(testTask.timeInterval);
NSString *string = [NSString stringWithFormat:@"%02u:%02u:%02u",
seconds / 3600, (seconds / 60) % 60, seconds % 60];
timerLabel.text = string;
NSLog(@"%f", testTask.timeInterval);
}