Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access the remaining time of a non repeating NSTimer

I'm trying to access the remaining time of an NSTimer X. I want to update the title of a button every second to reflect remaining mm:ss until zero. I couldn't find anything here.

For example: [btY setTitle:[What to insert here?] forState:UIControlStateSelected];

Or would you rather solve this in a different way?

like image 914
Coltan Avatar asked Jul 01 '12 18:07

Coltan


2 Answers

You can use fireDate

NSTimer *timer = [NSTimer timerWithInterval:1.0 target:self selector:@selector(updateButton) userInfo:nil repeats:YES];


- (void)updateButton:(NSTimer*)timer
{
    float timeRemaining = timer.fireDate.timeIntervalSinceNow;
    // Format timeRemaining into your preferred string form and 
    // update the button text
}
like image 191
Shammi Avatar answered Nov 20 '22 21:11

Shammi


This is generally not how you would solve this.

Create a repeating NSTimer set to the resolution at which you want to update the button instead.

So for instance, if you want your button to change every second until zero, create a NSTimer like so:

NSTimer *timer = [NSTimer timerWithInterval:1.0 target:self selector:@selector(updateButton) userInfo:nil repeats:YES];

Then implement updateButton; basically have a counter for remaining seconds, and every time updateButton gets called, decrease the counter by one, and update the title of the button.

like image 20
houbysoft Avatar answered Nov 20 '22 23:11

houbysoft