Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call a method repeatedly without blocking the UI?

Pretty generic question, is there a way to call a method I have every so often with the application without blocking the UI load?

like image 947
Timothy Frisch Avatar asked Dec 05 '22 07:12

Timothy Frisch


2 Answers

You can use Grand Central Dispatch for this:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, kNilOptions), ^{
    // Call your method.
});
like image 181
geraldWilliam Avatar answered Dec 06 '22 19:12

geraldWilliam


You definitely want to use Grand Central Dispatch to do this, but I'd just like to point out that GCD has a method build just for this kind of thing. dispatch_apply() executes its block a specified number of times on a queue of your choosing, of course, tracking which iteration you're on along the way. Here's an example:

size_t iterations = 10;

dispatch_queue_t queue = dispatch_queue_create("com.my.queue", DISPATCH_QUEUE_SERIAL);

dispatch_apply(iterations, queue, ^(size_t i) {
    NSLog(@"%zu",i);// Off the main thread.

    dispatch_async(dispatch_get_main_queue(), ^{
        // Go back to main queue for UI updates and such
    });
});
like image 20
Mick MacCallum Avatar answered Dec 06 '22 20:12

Mick MacCallum