views:

748

answers:

1

Hi Everyone:

I am wondering if there is some way that I can create a timer that countdown from a given time. For example, say I want this timer to last an hour. There will be a NSTextField that will show the time remaining (ex. 25 minutes), and will auto update every minute to the new value. And then, when an hour is finally passed, it will run some function. I have seen people suggesting NSTimer and NSDate for this, but am wondering what you all could suggest.

Thanks!

EDIT: My current code (timeInstance is an instance variable):

- (void)awakeFromNib:
{
timeInstance = [[NSDate date] addTimeInterval:(10 * 60)];
[timeInstance retain];

[timer invalidate];
timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timer:) userInfo:NULL repeats:YES];
}

- (void)timer:(NSTimer *)myTimer
{
NSDate *now = [NSDate date];
// Compare
}
+1  A: 

NSTimer and NSDate sounds perfectly reasonable.

EDIT: As a side note, it might be a good idea to increase the frequency as the target time approaches; allowing you to change from hour display to minute display to second display.

Williham Totland
Do you have any links that could describe how to create the countdown effect? It seems that most people are just talking about counting up.
PF1
Counting down is just like counting up. You take the difference between the target date and the current date.
Williham Totland
Would you mind taking a look at my code (in the main post)... I just can't figure out what to do next.
PF1
What you would do next is exactly what you said you wanted to do: Put the time remaining into the field, and test whether the countdown has finished, and do what you were waiting for if it has.
Peter Hosey
Hi Peter: My problem is that I don't know how to find the amount of time in between. Knowing the answer to that will allow me to put the time into the field and test if the time is less then 0 minutes.
PF1
This is a feature of NSDate. See the documentation: http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/
Peter Hosey