Reputation: 1
I searched around the internet for an answer but with no luck. I tried
- (void)viewDidLoad {
[super viewDidLoad];
twoMinTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timer) userInfo:nil repeats:YES]; }
- (void)timer {
for (int totalSeconds = 120; totalSeconds > 0; totalSeconds--){
timerLabel.text = [self timeFormatted:totalSeconds];
if ( totalSeconds == 0 ) {
[twoMinTimer invalidate];
} } }
but it didn't work, the label went from 2.00 to 0.01 when I went to that view and then it just stopped.
Any advice would be greatly appreciated - Philip
Upvotes: 0
Views: 3691
Reputation: 43330
You're using a one off for loop instead of simply decrementing the total amount of time. Try this:
- (void)viewDidLoad {
[super viewDidLoad];
totalSeconds = 120;
twoMinTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(timer)
userInfo:nil
repeats:YES];
}
- (void)timer {
totalSeconds--;
timerLabel.text = [self timeFormatted:totalSeconds];
if ( totalSeconds == 0 ) {
[twoMinTimer invalidate];
}
}
Declare totalSeconds
as an int.
EDIT: My absolute thanks for @JoshCaswell and @MichaelDorst for the suggestions and code formatting respectively. NSTimer is in no way an accurate representation of time, and is definitely not accurate enough for a stopwatch or counter. Instead, NSDate's +dateSinceNow
would be a more accurate substitute, or even the progressively lower level CFAbsoluteTimeGetCurrent()
and mach_absolute_time()
are accurate to sub-milliseconds
Upvotes: 7