How do i create a countdown timer in xcode 4.5 [closed]
-
02-07-2021 - |
Question
Ok i want to create MULTIPLE timers that all start at a different time (25, 50,1 min, 1min 30s...) but i dont know how to make it stop when it reaches 0 and when it does reach zero, bring the "Player" to another view.
Heres my .h file
@interface ViewController :UIViewController {
IBOutlet UILabel *seconds;
NSTimer *timer;
int MainInt;
}
@end
And heres my .m file
@implementation ViewController
-(void)countDownDuration {
MainInt -= 1;
seconds.text = [NSString stringWithFormat:@"%i", MainInt];
}
-(IBAction)start:(id)sender {
MainInt = 25;
timer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(countDownDuration)
userInfo:nil
repeats:YES];
}
@end
Solution
NSTimer doesn't do this automatically, but it's trivial to add it to your countDownDuration method. For example:
-(void)countDownDuration {
MainInt -= 1;
seconds.text = [NSString stringWithFormat:@"%i", MainInt];
if (MainInt <= 0) {
[timer invalidate];
[self bringThePlayerToAnotherView];
}
}
Of course you want to create multiple timers. You could store each one in a different variable and give each one a different selector. But if you look at the documentation for NSTimer, the callback method actually takes the timer object as a selector; you're ignoring it, but you shouldn't be.
And meanwhile, you can store an object of any type you want as the userInfo for the timer, so that's a good place to stash a separate current countdown value for each timer.
So, you can do something like this:
-(void)countDownDuration:(NSTimer *)timer {
int countdown = [[timer userInfo] reduceCountdown];
seconds.text = [NSString stringWithFormat:@"%i", countdown];
if (countdown <= 0) {
[timer invalidate];
[self bringThePlayerToAnotherView];
}
}
-(IBAction)start:(id)sender {
id userInfo = [[MyCountdownClass alloc] initWithCountdown:25];
timer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(countDownDuration:)
userInfo:userInfo
repeats:YES];
}
I've left a few details unwritten (like the definition of MyCountdownClass
—which has to include method initWithCountdown:
and reduceCountdown
that do the right thing), but they should all be pretty simple. (Also, presumably you want a userInfo that stores more than just the countdown value—e.g., if each timer sends the player to a different view, you've got to stash the view there as well.)
PS, notice that you now need @selector(countDownDuration:)
. Newcomers to ObjC screw this up all the time. countDownDuration:
and countDownDuration
are completely unrelated selectors.
PPS, the full definition of MyCountdownClass
will have to be visible in countDownDuration:
(unless you have some other class with the same selectors). You may want to explicitly cast the result of userInfo
to MyCountdownClass *
to make things clearer.