开发者

How to make a persistent (multitasking-aware) stopwatch?

开发者 https://www.devze.com 2023-03-31 03:41 出处:网络
I am using NSTimer to make a stopwatch. I would like it to continue working if the user switches to a different app, but right now it only works when the app is running. I figure that this is probably

I am using NSTimer to make a stopwatch. I would like it to continue working if the user switches to a different app, but right now it only works when the app is running. I figure that this is probably pretty simple to fix by recording a timestamp when the timer starts, but I'm not really sure how to reconcile that with the ability to pause/restart the timer in the middle.

My code:

-(IBAction)start;
{
    if(sharedInstance.timer == nil){
    sharedInstance.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self  开发者_运维问答   selector:@selector(showActivity) userInfo:nil repeats:YES];
    sharedInstance.timerRunning = YES;
    }
}


-(IBAction)stop;
{
    [sharedInstance.timer invalidate];
    sharedInstance.timer = nil;
    sharedInstance.timerRunning = NO;
}


-(void)showActivity;
{
    sharedInstance.elapsedTime += 1;

    int hours = sharedInstance.elapsedTime / 3600 ;
    int minutes = sharedInstance.elapsedTime / 60 - hours * 60; 
    int seconds = sharedInstance.elapsedTime - hours * 3600 - minutes * 60;

    sharedInstance.timeString = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];
    self.readout.text = sharedInstance.timeString;
}

-(void)viewDidLoad {
    sharedInstance = [DataSingleton sharedInstance];
    if (sharedInstance.timeString==nil) {
    sharedInstance.timeString=@"00:00:00";
    }
    self.readout.text = sharedInstance.timeString;
    [sharedInstance.timer invalidate];
    sharedInstance.timer = nil;
    if(sharedInstance.timerRunning) {
        [self start];
    }
    [super viewDidLoad];
}

-(void)reset {
    [self stop];
    sharedInstance.elapsedTime = 0;
    sharedInstance.timeString = @"00:00:00";
    self.readout.text = sharedInstance.timeString;
} 


Every time you call showActivity you could get a new time stamp and subtract the old one from it getting the change in time. Then add that to elapsedTime instead of 1.

0

精彩评论

暂无评论...
验证码 换一张
取 消