1

我的实用程序将有 20 个单独的计时器,布局如下:

- (void)updateTimer
{
NSDate *currentDate = [NSDate date];
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate];
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"mm:ss"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
NSString *timeString=[dateFormatter stringFromDate:timerDate];
stopWatchLabel.text = timeString;
[dateFormatter release];
}

- (IBAction)onStartPressed:(id)sender {
startDate = [[NSDate date]retain];

// Create the stop watch timer that fires every 1 s
stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                                  target:self
                                                selector:@selector(updateTimer)
                                                userInfo:nil
                                                 repeats:YES];
}

- (IBAction)onStopPressed:(id)sender {
[stopWatchTimer invalidate];
stopWatchTimer = nil;
[self updateTimer];
}

我想将所有时间间隔加在一起,并将它们显示为字符串。我以为这很容易,但我就是无法做到。我需要总结 NSTimeIntervals,对吧?

4

1 回答 1

0

您可以采取几种方法。一种是创建一个可以查询其状态(正在运行、已停止、未启动……)及其当前时间间隔的计时器类。将所有计时器添加到集合中,例如NSMutableArray. 然后,您可以遍历集合中的所有计时器,对于那些停止的计时器,获取其时间间隔,并将它们相加。类的部分标头MyTimer

enum TimerState {
    Uninitialized,
    Reset,
    Running,
    Stopped
};

typedef enum TimerState TimerState;

#import <Foundation/Foundation.h>

@interface MyTimer : NSObject

@property (nonatomic) NSTimeInterval timeInterval;
@property (nonatomic) TimerState state;

- (void) reset;
- (void) start;

@end 

声明你的数组:

#define MAX_TIMER_COUNT 20
NSMutableArray *myTimerArray = [NSMutableArray arrayWithCapacity:MAX_TIMER_COUNT];

将每个计时器添加到数组中:

MyTimer *myTimer = [[MyTimer alloc] init];
[myTimerArray addObject:myTimer];

在适当的时候,迭代计时器的集合并对计时器的时间间隔求和Stopped

NSTimeInterval totalTimeInterval = 0.0;
for (MyTimer *timer in myTimerArray){
    if (timer.state == Stopped) {
        totalTimeInterval += timer.timeInterval;
    }
}
于 2012-11-04T19:37:15.000 回答