NSTimer causing some weird delay
Ok my first app ever is a timer. Right after I made hello world as the convention seems to be. I am using the NSTimer class as my timer and I fire it every second and then I change the text in a UILabel. Now this all works very good except for my very first run. Each time I run the app in the simulator and I start the timer their is a weird delay on my last second, it will freeze for about 2 seconds and then continue as if nothing is wrong. And it then works for every set that runs.
Here is the code where I set up the NSTimer:
theTimer = [NSTimer scheduledTimerWithTimeInterval:(1.0) target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
Then in the onTimer method I call updateLabel
countDownLabel.text = [NSString stringWithFormat:@"%02d:%02d", startMin,startSec];
//Check if sets are complete
if(setCount <= numOfSets)
{
setLabel.text = [NSString stringWithFormat:@"Set %02d of %02d", setCount, numOfSets];
//check if timer is complete
if(startMin <= 0 && startSec <= 0)
{
countDownLabel.textColor = [UIColor greenColor];
//run interval timer when timer is complete
if(intervalBetweenSets <= intervalBetweenSetsSetting)
{
setLabel.text = [NSString stringWithFormat:@"Starting set"];
intervalBetweenSets++;
intervalCounterSec--;
countDownLabel.text = [NSString stringWithFormat:@"00:%02d", intervalCounterSec];
}
else
{
//RESET values on timer label
TimerSettings *myTimer = [TimerSettings sharedManager ];
startMin = myTimer.min;
startSec = myTimer.sec;
intervalBetweenSets = 0;
intervalCounterSec = intervalBetweenSetsSetting+1;
countDownLabel.textColor = [UIColor redCo开发者_高级运维lor];
countDownLabel.text = [NSString stringWithFormat:@"%02d:%02d", startMin,startSec];
setLabel.text = [NSString stringWithFormat:@"Set %02d of %02d", setCount, numOfSets];
}
}
else
{
//Actual timer for display
if(startSec == 0)
{
startMin = startMin - 1;
}
startSec = startSec - 1;
if(startSec == -1)
{
startSec = 59;
}
if(startMin <= 0 && startSec < 1)
{
//increment number of completed sets
setCount++;
//play sound when timer completes
if (audioPlayer == nil)
;
else
{
[audioPlayer play];
}
}
countDownLabel.text = [NSString stringWithFormat:@"%02d:%02d", startMin,startSec];
}
}
The thing is I don't know if it is some problem with the timer or if it has something to do with my logic, if anything is unclear of what I am doing please ask away and I will clarify.
Thanks
You shouldn't use NSTimer to keep time if that is what you are trying to do, NSTimers are conceptually put into the event cue and so can only fire when your programming is waiting for input from the event cue. Yo can use NSTimers to tell you fields to update the display of itself but to get the amount of time passed you should either use NSDate methods or the equivelent C functions.
精彩评论