Reputation:
I am showing a count down timer using UILabel
and NSTimer
-
-(void)a_Method
{
[coolTimeLbl setNeedsDisplay];
coolTime = 5; // it is an int
coolingTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(cooling) userInfo:nil repeats:YES]; // NSTimer
}
-(void)cooling
{
if (coolTime>0)
{
coolTime = coolTime-1;
NSLog(@" coolTime----%@",coolTime);
coolTimeLbl.text =[NSString stringWithFormat:@"%d",coolTime];
NSLog(@" coolTimeLbl----%@",coolTimeLbl.text);
}
else
{
[coolingTimer invalidate];
coolingTimer = nil;
}
}
The first time everything works fine and I am getting coolTimeLbl.text
as - 4 3 2 1 0
But the second time when I call aMethod
, coolTimeLbl
is not getting updated properly - it is like 3 2 0 etc (some weird behavior)
However both NSLogs
(coolTime
& coolTimeLbl
) print perfectly all the times and values.
Why does this happen? I tried many ways like NSNotification
etc.
Please help me to fix this.
Upvotes: 0
Views: 120
Reputation: 2896
Had the same issue in one of my viewControllers and another one was working OK with same NSTimer code. Looked at about 20 SO threads to get it solved. No luck. In my case
myLabel.opaque = false
solved it. Don't ask me why.
Upvotes: 0
Reputation: 1933
If you're calling a_Method more than once before coolingTimer invalidates itself, the timer will tick more than once.
You should add some boolean like ;
BOOL isTimerValid;
in a_Method,
if(!isTimerValid)
{
isTimerValid = YES;
coolingTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(cooling) userInfo:nil repeats:YES]; // NSTimer
}
in cooling,
else
{
isTimerValid = NO;
....
}
Upvotes: 1