NSTimer Lap Time iPhone

时间:2011-11-19 21:19:13

标签: iphone objective-c xcode nstimer

这是我的秒表代码。这一切都有效,除了圈按钮功能。我怎样才能实现一个单圈时间,当按下ib动作“圈”时,它会将当前时间存储在一个数组中并列出视图上的单圈时间?

我已经尝试过创建一个数据库,但对于这种性质来说,这似乎很复杂。

#import "FirstViewController.h"

@implementation FirstViewController
@synthesize start;
@synthesize stop;
@synthesize lap;
@synthesize reset;
@synthesize lapLabel;
@synthesize stopWatchLabel;

NSDate *startDate;
NSDateFormatter *dateFormatter;
NSTimer *stopWatchTimer;
NSTimeInterval secondsAlreadyRun;


int touchCount;



-(void)showActivity:(NSTimer *)tim {

    NSDate *currentDate = [NSDate date];
    NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate];
    // Add the saved interval
    timeInterval += secondsAlreadyRun;
    NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"mm:ss.SS"];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
    NSString *timeString=[dateFormatter stringFromDate:timerDate];
    stopWatchLabel.text = timeString;

}

- (IBAction)onStartPressed:(UIButton *)sender {

    stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1/10 
                                                      target:self 
                                                    selector:@selector(showActivity:) 
                                                    userInfo:nil 
                                                     repeats:YES];
    // Save the new start date every time
    startDate = [[NSDate alloc] init]; // equivalent to [[NSDate date] retain];
    [stopWatchTimer fire];

    touchCount +=1;
    if (touchCount == 1) 
    {
        start.hidden = YES;
        stop.hidden = NO;
        reset.hidden = YES;
        lap.hidden = NO;
        touchCount = 0;
    }

}

- (IBAction)onStopPressed:(UIButton *)sender {
    // _Increment_ secondsAlreadyRun to allow for multiple pauses and restarts
    secondsAlreadyRun += fabs([startDate timeIntervalSinceNow]);
    [stopWatchTimer invalidate];
    stopWatchTimer = nil;
    stop.hidden = YES;
    start.hidden = NO;
    reset.hidden = NO;
    lap.hidden = YES;

}

- (IBAction)reset:(UIButton *)sender; {
    secondsAlreadyRun = 0;
    stopWatchLabel.text = @"00:00.00";
}

- (IBAction)lap:(UIButton *)sender; {
    //Lap Code will go here.

}

- (void)viewDidUnload {
    [self setStart:nil];
    [self setStop:nil];
    [self setLap:nil];
    [self setReset:nil];
    [self setLap:nil];
    [super viewDidUnload];
}
@end

1 个答案:

答案 0 :(得分:0)

只需使用存储在类中的NSMutableArray。每次人们点击圈按钮 比如打电话

NSMutableArray *lapTimes;

在你的方法中做:

- (IBAction)lap:(UIButton *)sender {
    double timeSinceStart = [startDate timeIntervalSinceNow];
    [lapTimes addObject:[NSNumber numberWithDouble:-timeSinceStart]];
}

timeIntervalSinceNow将返回NSDate对象与现在之间的时间差,以秒为单位。如果NSDate现在早些时候(就像你的情况一样),返回的数字将是负数,所以你必须反转它。