iphone - Strange delay on NSTimer -


i having following code in viewdidload method. updating label every second. when run code shows dummy text, waits bit shows 8 sec instead of 9 8..

so seems skipping 9, possible fix this? should have rounded decimals when calculate time left?

thank time!

//just dummy text self.lbltime.text = @"tid: 0h 0min 10sec";  nsdate *expiredate = [[nsdate alloc] initwithtimeinterval:10 sincedate:[nsdate date]]; self.expires = expiredate; [expiredate release];   self.timer = [nstimer scheduledtimerwithtimeinterval:1.0 target:self selector:@selector(updatetimerdisplay) userinfo:nil repeats:yes]; [[nsrunloop currentrunloop] addtimer:self.timer formode:uitrackingrunloopmode];  

in updatetimerdisplay have:

//gets time right     nsdate *now = [nsdate date];  //stores difference in seconds between when test started , now. nstimeinterval interval = [self.expires timeintervalsincedate:now];  //gets number of hours nsinteger hours = interval / 3600;  interval = (int)interval % 3600;  //gets number of seconds nsinteger minutes = interval / 60;  interval = (int)interval % 60;  nsinteger seconds = interval;  //updates label self.lbltime.text = [nsstring stringwithformat:@"time: %dh %dmin %dsec", hours, minutes, seconds]; 

firstly, i'd recommend using [nsdate datewithtimeintervalsincenow:10] instead of [[nsdate alloc] initwithtimeinterval:10 sincedate:[nsdate date]] , [self.expires timeintervalsincenow] instead of [self.expires timeintervalsincedate:[nsdate date]]. these more succinct.

also remember since self.expires earlier date now in second set of code, interval negative, because interval since now interval since self.expires. code doesn't appear take fact account.

finally, if set expires 10 seconds future, , timer fire in second, may have missed 9 second mark. because timers inherently not 100% accurate, , more 1 second may have elapsed. 1.01 seconds has elapsed, leaves 10 - 1.01 = 8.99 seconds remaining, using integer math truncated 8 seconds remaining. seems me cause of error. i'd recommend firing timer more every second (every tenth of second or so) avoid these problems.

if you're interested, example of temporal aliasing.


Comments

Popular posts from this blog

linux - Mailx and Gmail nss config dir -

c# - Is it possible to remove an existing registration from Autofac container builder? -

php - Mysql PK and FK char(36) vs int(10) -