【发布时间】:2017-06-25 09:19:08
【问题描述】:
我想使用NSTimer 来增加标签上显示的数字。
这是我的代码:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.numberLabel = [[UILabel alloc]initWithFrame:CGRectMake(90, 90, 90, 30)];
[self.view addSubview:self.numberLabel];
self.timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(refreshText) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop]addTimer:self.timer forMode:NSRunLoopCommonModes];
}
- (void)refreshText{
NSDate *beginDate = [NSDate date];
static NSInteger a = 0;
a ++;
self.numberLabel.text = [NSString stringWithFormat:@"%ld",a];
if (a == 1000) {
NSDate *endDate = [NSDate date];
NSTimeInterval durationTime = [endDate timeIntervalSinceDate:beginDate];
NSTimeInterval intervalTime = self.timer.timeInterval;
NSLog(@"durationTime = %f",durationTime);
NSLog(@"intervalTime = %f",intervalTime);
[self.timer invalidate];
self.timer = nil;
}
}
然后我将计时器的 timeInterval 从 0.01 更改为 0.001,控制台显示:
让我困惑的是,为什么当timeInterval为0.001时,durationTime不是0.0000056。而且,NSTimer的timeInterval有最小值我们可以设置吗?
【问题讨论】:
-
NSTimer 的分辨率充其量约为0.01s,精度不高。超过 0.02 秒的更新频率无论如何都不会引起注意
-
您真的不想编写一个具有如此快速触发计时器的应用程序。它只会消耗电池寿命并使应用程序无响应。
标签: ios objective-c nstimer