【问题标题】:How Do I write a Timer in Objective-C?如何在 Objective-C 中编写计时器?
【发布时间】:2011-03-31 23:29:34
【问题描述】:

我正在尝试使用 NSTimer 制作秒表。

我给出了以下代码:

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

它无法在几毫秒内工作。这需要超过 1 毫秒。

【问题讨论】:

    标签: iphone objective-c timer nsdate nstimer


    【解决方案1】:

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

    你想要的是一个高分辨率计时器类(使用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
    

    【讨论】:

    • 这个类不包含dealloc方法。这不会泄漏吗?
    • 如果我想使用这个类来重复执行一段代码(比如重复的 NSTimer),我该怎么做呢?
    • 这个答案太可笑了,只有 1 票(现在是 2 票)。
    • 由于[NSDate date]startTimerstopTimer 中自动释放,因此无法保证这些对象在稍后尝试使用它们之前由自动释放池释放,例如timeElapsedInSeconds。您应该将它们保留在startTimerstopTimer 中,并在其中释放之前的实例(以及在dealloc 方法中)以防止内存访问问题。
    • @yourfriendzak:我指的是在startTimerstopTimer 中构造的NSDate 对象;它们是自动释放的,因此它们的保留计数为零,并且它们可以随时由自动释放池释放。我可能会将startend 设为@property (nonatomic,retain),然后使用self.start = [NSDate date]self.end = [NSDate date]。在dealloc 中,需要通过覆盖dealloc 方法(当然应该在最后的超类中调用dealloc)来释放[start release][end release]start and end`。
    猜你喜欢
    • 2013-11-26
    • 2011-08-08
    • 1970-01-01
    • 2020-07-30
    • 1970-01-01
    • 2010-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多