如何在Objective-C中编写定时器? [英] How Do I write a Timer in Objective-C?

查看:150
本文介绍了如何在Objective-C中编写定时器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用NSTimer进行秒表。

I am trying to make a stop watch with NSTimer.

我提供了以下代码:

 nst_Timer = [NSTimer scheduledTimerWithTimeInterval:0.001 target:self selector:@selector(showTime) userInfo:nil repeats:NO];

并且它在毫秒内无法正常工作。它需要超过1毫秒。

and it is not working in milliseconds. It takes more than 1 millisecond.

推荐答案

不要使用 NSTimer 那样。 NSTimer通常用于在某个时间间隔触发选择器。它的精度不高,不适合你想做的事情。

Don't use NSTimer that way. NSTimer is normally used to fire a selector at some time interval. It isn't high precision and isn't suited to what you want to do.

你想要的是一个高分辨率计时器类(使用 NSDate ):

What you want is a High resolution timer class (using NSDate):

输出:

Total time was: 0.002027 milliseconds
Total time was: 0.000002 seconds
Total time was: 0.000000 minutes

主要:

Timer *timer = [[Timer alloc] init];

[timer startTimer];
// Do some work
[timer stopTimer];

NSLog(@"Total time was: %lf milliseconds", [timer timeElapsedInMilliseconds]);  
NSLog(@"Total time was: %lf seconds", [timer timeElapsedInSeconds]);
NSLog(@"Total time was: %lf minutes", [timer timeElapsedInMinutes]);

编辑:为添加方法-timeElapsedInMilliseconds -timeElapsedInMinutes

Timer.h:

#import <Foundation/Foundation.h>

@interface Timer : NSObject {
    NSDate *start;
    NSDate *end;
}

- (void) startTimer;
- (void) stopTimer;
- (double) timeElapsedInSeconds;
- (double) timeElapsedInMilliseconds;
- (double) timeElapsedInMinutes;

@end

Timer.m

#import "Timer.h"

@implementation Timer

- (id) init {
    self = [super init];
    if (self != nil) {
        start = nil;
        end = nil;
    }
    return self;
}

- (void) startTimer {
    start = [NSDate date];
}

- (void) stopTimer {
    end = [NSDate date];
}

- (double) timeElapsedInSeconds {
    return [end timeIntervalSinceDate:start];
}

- (double) timeElapsedInMilliseconds {
    return [self timeElapsedInSeconds] * 1000.0f;
}

- (double) timeElapsedInMinutes {
    return [self timeElapsedInSeconds] / 60.0f;
}

@end

这篇关于如何在Objective-C中编写定时器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆