Ios 如何每秒更新当前时间?

Ios 如何每秒更新当前时间?,ios,Ios,我有一个显示时间的标签;但是,时间没有更新。时间会显示出来,但不会累计。将显示按下按钮的时间,该时间不变。这是我的密码 - (IBAction)startCamera:(id)sender { [self.videoCamera start]; NSDate *today = [NSDate date]; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@

我有一个显示时间的标签;但是,时间没有更新。时间会显示出来,但不会累计。将显示按下按钮的时间,该时间不变。这是我的密码

- (IBAction)startCamera:(id)sender
{
[self.videoCamera start];

NSDate *today = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"HH:mm:ss"];
NSString *currentTime = [dateFormatter stringFromDate:today];
[dateFormatter setDateFormat:@"dd.MM.yyyy"];
NSString *currentDate = [dateFormatter stringFromDate:today];


for (int i = 1; i <= 10; i--) {
Label1.text = [NSString stringWithFormat:@"%@", currentTime];
Label2.text = [NSString stringWithFormat:@"%@", currentDate];    
   }

}
-(iAction)startCamera:(id)发送方
{
[自拍照启动];
NSDate*今天=[NSDate日期];
NSDateFormatter*dateFormatter=[[NSDateFormatter alloc]init];
[日期格式化程序setDateFormat:@“HH:mm:ss”];
NSString*currentTime=[dateFormatter stringFromDate:today];
[日期格式化程序setDateFormat:@“dd.MM.yyyy”];
NSString*currentDate=[dateFormatter stringFromDate:today];

for(int i=1;iUI更新是使用在主线程上运行的事件循环执行的。for循环占用主线程,从不从启动函数返回。无论您在labelx.text中设置什么,都不会在屏幕上刷新,因为运行循环正在等待启动函数完成

您应该仔细阅读NSTimer,以使用最佳实践实现这一点

还有一种方法是使用延迟分派: (很抱歉,这是Swift,我不知道objective-C,但我相信你会明白的)


NSTimer可以工作,但不是很准确

当我需要精确的计时器时,我会使用CADisplaylink,尤其是在处理动画时。这可以减少视觉上的口吃

使用显示刷新是准确可靠的。但是,您不希望使用此方法进行繁重的计算

- (void)startUpdateLoop {
    CADisplayLink *displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(update:)];
    displayLink.frameInterval = 60;
    [displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
}

- (void)update {
    // set you label text here.
}

For循环在基于事件的系统中是令人讨厌的。我会寻找一些你可以监听的事件。查看
NSTimer
@KeithJohnHutchison你是什么意思?你有一个无限循环。For(int I=1;我使用间隔为1秒(1000毫秒)的NSTimer)我很惊讶NSTimer会如此不准确以至于无法达到1秒的精度。你测量过吗?用户会注意到时钟上的秒数是否延迟了半秒吗?NSTimer文档中的第三段。最终这取决于你使用它的目的。秒表/节拍器我会避免NSTimer.100ms当然值得注意。对于投票否决我的人,请解释原因。因此,即使根据规范,它的速度也足够快。100毫秒在动画场景中可能是值得注意的,但这在这里不适用。NSTimer刷新时钟的速度比要求的快10倍。因此,它确实取决于您使用它的目的。这在这里是非常合适的,比我下面建议的低级别方法或核心动画中的更低级别方法更合适。
- (void)startUpdateLoop {
    CADisplayLink *displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(update:)];
    displayLink.frameInterval = 60;
    [displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
}

- (void)update {
    // set you label text here.
}