7

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?

Philipp Schlösser
  • 5,179
  • 2
  • 38
  • 52
Coltan
  • 73
  • 1
  • 3

3 Answers3

16

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
}
pulse4life
  • 1,006
  • 10
  • 13
Shammi
  • 492
  • 5
  • 13
  • This is the right answer to the question "how do I access time remaining" on a timer, but the property is wrong (at least on iOS 8). It should be: `float timeRemaining = timer.fireDate.timeIntervalSinceNow;` – itnAAnti Aug 21 '15 at 20:29
2

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.

houbysoft
  • 32,532
  • 24
  • 103
  • 156
  • thanks a lot even if this sounds like tons of text for such an easy job :P – Coltan Jul 01 '12 at 18:22
  • @Coltan: glad it helped. If your problem is resolved, you can mark this as the accepted answer using the green checkmark on the left. – houbysoft Jul 01 '12 at 18:24
0

You will not be able to get this kind of information, instead you will need to run the timer several times, for example, if you want to update the button with a text one time each 30 seconds, instead of starting a timer with 30 seconds start a timer with 1 sec and repeat it 30 times

Omar Abdelhafith
  • 21,163
  • 5
  • 52
  • 56