我的实用程序应用程序将有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,对吧?
答案 0 :(得分: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;
}
}