objective c - How to remove timer from runloop immediately -


i have timer triggered in 5 seconds added global queue, though invalidating after 2 seconds run loop won't terminate till 5 seconds. in following snippet backgroundtimer instance var, , run member function. what's wrong in following code blocking run loop termination.

    dispatch_async(dispatch_get_global_queue(dispatch_queue_priority_default, 0), ^{      _backgroundtimer = [nstimer timerwithtimeinterval:5 target:self selector:@selector(run) userinfo:nil repeats:no];     [ [nsrunloop currentrunloop] addtimer:_backgroundtimer formode:nsrunloopcommonmodes];     [[nsrunloop currentrunloop] run];      nslog(@"run loop terminated");  });  dispatch_after(dispatch_time(dispatch_time_now, (int64_t)(2 * nsec_per_sec)), dispatch_get_global_queue(dispatch_queue_priority_default, 0), ^{     [_backgroundtimer invalidate];     _backgroundtimer=nil;  }); 

the first problem here timer being added run loop on arbitrary background thread. (i.e. thread have been created gcd service background queue) can this, kind of makes no sense.

that aside, said want have happen run loop exit, in documentation -run method, says following:

manually removing known input sources , timers run loop not guarantee run loop exit. os x can install , remove additional input sources needed process requests targeted @ receiver’s thread. sources therefore prevent run loop exiting.

if want run loop terminate, shouldn't use method. instead, use 1 of other run methods , check other arbitrary conditions of own, in loop.

you need spin event loop if want exit when timer invalid. example:

while (_backgroundtimer.valid && [[nsrunloop currentrunloop] runmode:nsdefaultrunloopmode beforedate:[nsdate datewithtimeintervalsincenow: 0.1]]); 

this exit run loop maximum of 0.1 (- epsilon) seconds after timer invalidated.


Comments

Popular posts from this blog

java - Plugin org.apache.maven.plugins:maven-install-plugin:2.4 or one of its dependencies could not be resolved -

Round ImageView Android -

How can I utilize Yahoo Weather API in android -