我编译了以下代码,没有明显的运行时错误;但是,当我运行时,显示屏在00:00:01冻结。如果我只显示seconds属性,它可以工作。有没有人看到我在这段代码中遗漏的明显疏忽?我知道启动按钮可能存在内存泄漏,但我最终会解决这个问题。
提前致谢。
#import "StopwatchViewController.h"
@implementation StopwatchViewController
- (IBAction)start{
//creates and fires timer every second
myTimer = [[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(showTime) userInfo:nil repeats:YES]retain];
}
- (IBAction)stop{
[myTimer invalidate];
myTimer = nil;
}
- (IBAction)reset{
[myTimer invalidate];
time.text = @"00:00:00";
}
(void)showTime{
int currentTime = [time.text intValue];
int new = currentTime +1;
int secs = new;
int mins = (secs/60) % 60;
int hours = (mins/60);
time.text = [NSString stringWithFormat:@"%.2d:%.2d:%.2d",hours, mins, secs];
}
答案 0 :(得分:3)
你从
得到0int currentTime = [time.text intValue];
因为text
中的字符串:
@"00:00:00"
无法转换为int
,因此每次计时器触发时,都会添加1到0并获得1,然后显示。无论如何,数学将是不准确的,因为分钟和秒是“基数为60”* - 您需要执行与分离小时/分钟/秒相关的数学运算的反向,以便再次获得总秒数。您可以将currentTime
设为ivar,并保留其中的总秒数。
*这不是真正的所谓;我确定有一个特定的词。
答案 1 :(得分:2)
- (IBAction)start{
currentTime = 0;
//creates and fires timer every second
myTimer = [[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(showTime) userInfo:nil repeats:YES]retain];
}
- (IBAction)stop{
[myTimer invalidate];
myTimer = nil;
}
- (IBAction)reset{
[myTimer invalidate];
time.text = @"00:00:00";
}
- (void)showTime{
currentTime++;
int secs = currentTime % 60;
int mins = (currentTime / 60) % 60;
int hour = (currentTime / 3600);
time.text = [NSString stringWithFormat:@"%.2d:%.2d:%.2d",hour, mins, secs];
}