进入新公司,要求做一个秒表作为新人的第一个练手项目,用了1天时间基本实现了需求。但是在实现的过程中,原不起眼的小项目中还是有一些需要注意的地方。
用代码实现秒表的原理,就是用定时器设定间隔时间后调用我所构造的时间结构中的整型变量,然后通过lable用字符串将不同变化的整型变量表示出来。
我是用2个Lable接受的值,一个为毫秒,一个为时、分、秒。100ms—》1s
- (void)updateTime:(NSTimer *)timer{
timeString = [NSString string];
// 判断时间结构,完整的显示出当前时间
numbers++;
if (numbers == 100) {
numbers = 00;
seconds++;
}
if (seconds == 60) {
seconds = 00;
minutes++;
}
if (minutes == 60) {
minutes = 00;
hours++;
}
if (hours == 24) {
hours = 0;
}
if (minutes < 10) {
if (seconds <10) {
timeString = [NSString stringWithFormat:@"%d:0%d:0%d",hours,minutes,seconds];
}else{
timeString = [NSString stringWithFormat:@"%d:0%d:%d",hours,minutes,seconds];
}
}else {
timeString = [NSString stringWithFormat:@"%d:%d:%d",hours,minutes,seconds];
}
[self performSelectorOnMainThread:@selector(refleshTime) withObject:nil waitUntilDone:YES];
}
这个函数是用来构造时间的结构的。这个结构要放在子线程中的,否则当我拖拽表格的时候会引起主线程的堵塞。下面的方式是在我所开启的子线程中开启定时器。在子线程中开启定时器要将定时器加入到Runloop中。并且不要忘记调用【【NSRunLoop CurrenRunLoop】run】;
timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(updateTime:) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop]addTimer:timer forMode:NSDefaultRunLoopMode];
[[NSRunLoop currentRunLoop] run];
同时,在计算2个NSDate的时间差可以用 NSTimeInterval heh = [date1 timeIntervalSinceDate:date];
方法实现。 NSTimeInterval是一个double类型,所得的结果是秒为单位,可以通过所得的这个数据按照其他格式输出,计算出其分钟和小时。
;