iphone - Thread and NSTimer -
i making application has timer. count minutes , seconds given time down 0. when happen launch alertview.
my structure this:
mainthread method allocate new thread , initialize it. entrypoint(method) thread has timer invokes method calculating time left, , if time up, displays alertview.
however, correct? because updating gui thread main...and bad right? , displaying alertview thread.
i thought of making method encapsulate logic updating , displaying alertview , in method nstimer invokes use performselectorinmainthread, correct?
thanks time.
assuming it's simple determine how time left, run timer on main thread. timer gets attached current runloop, it's not blocking anywhere, , callback method shouldn't take inordinate amount of time run, , can therefore update ui nicely.
- (void) initializetimerwithendtime: (nsdate *) endtime { // call on main thread & it'll automatically // install timer on main runloop self.countdowntimer = [nstimer scheduledtimerwithtimeinterval: 1.0 target: self selector: @selector(timertick:) userinfo: endtime repeats: yes]; #if __target_os_iphone__ // fire while tracking touches [[nsrunloop mainrunloop] addtimer: self.countdowntimer formode: uitrackingrunloopmode]; #else // fire while tracking mouse events [[nsrunloop mainrunloop] addtimer: self.countdowntimer formode: nseventtrackingrunloopmode]; // fire while showing application-modal panels/alerts [[nsrunloop mainrunloop] addtimer: self.countdowntimer formode: nsmodalpanelrunloopmode]; #endif } - (void) cancelcountdown { [self.countdowntimer invalidate]; self.countdowntimer = nil; } - (void) timertick: (nstimer *) atimer { nsdate * enddate = [timer userinfo]; nsdate * = [nsdate date]; // have passed end date? if ( [enddate laterdate: now] == ) { // show alert [self cancelcountdown]; return; } // otherwise, compute units & show nsuinteger units = nshourcalendarunit|nsminutecalendarunit|nssecondcalendarunit; nsdatecomponents * comps = [[nscalendar currentcalendar] components: units fromdate: [nsdate date] todate: enddate options: 0]; [self.clockview sethours: comps.hour minutes: comps.minute seconds: comps.second]; }
Comments
Post a Comment