如何添加多个定时器的输出

我的实用程序应用程序将有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]; } 

我想添加所有的时间间隔在一起,并显示为一个string。 我觉得这很容易,但我不明白。 我需要总结NSTimeIntervals,对吧?

你可以采取几种方法。 一个是创build一个可以查询其状态(运行,停止,未启动,…)和当前时间间隔的计时器类。 将所有的定时器添加到一个集合,如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; } }