GCD timer never fires

I have one iOS application with one view with the following in the -viewDidLoad view:

 dispatch_queue_t q_default; q_default = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, q_default); //run event handler on the default global queue dispatch_time_t now = dispatch_walltime(DISPATCH_TIME_NOW, 0); dispatch_source_set_timer(timer, now, 30ull*NSEC_PER_SEC, 5000ull); dispatch_source_set_event_handler(timer, ^{ printf("test\n"); }); dispatch_resume(timer); 

This is taken directly from the documents (with the exception of the simplified argument to printf() ). A block is never executed - can someone tell me why?

Additional Information

I tried to use this in a large application to no avail. Then I retreated to the barebones application, tried on and off with ARC, tried this code in -appDidFinishLaunching... , all with no luck. I can surround this NSLog s code, both of which are printed. I checked the timer - this is not nil .

+4
source share
2 answers

So, the problem was that I lost the timer link when the surrounding area was destroyed. Changing timer to ivar instead of automatic variable of fixed things ...

+5
source

In the documentation for dispatch_source_create :

Sending sources are created in a paused state. After creating the source and setting any desired attributes (for example, a handler or context), your application must call dispatch_resume to start event delivery.

Thus, your timer never fires because it is paused. To complete its suspension, you need to call dispatch_resume .

+4
source

Source: https://habr.com/ru/post/1446599/


All Articles