Search code examples
iphoneobjective-ccocoa-touchnstimeinterval

running a time interval computation in the background


I have a NSTimeInterval which is basically

NSTimeInterval interval = [date1 timeIntervalSinceDate: [NSDate date]];

I want this computation to be always running in the background when I am in a view X, so I can display a timer counting down in a UILabel.. how do I do this? It's like in the groupon iphone app, but it doesn't show it in details of seconds


Solution

  • You could use an NSTimer to get a method called at a set time interval (however this is all performed on the main thread, not on a background thread):

    - (void)setupTimer {
        //Start a timer to call update updateInterval: every 1 second
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                                   target:self
                                                   selector:@selector(updateInterval:)
                                                 userInfo:nil
                                                  repeats:YES];
    }
    
    - (void)updateInterval:(NSTimer *)timer {
        NSTimeInterval interval = [date1 timeIntervaleSinceDate:[NSDate date]];
        //Do other things like updating the label
    }