Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating UI components from an async callback (dispatch_queue)

how can i update GUI elements with values from a queue? if i use async queue construct, textlable don't get updated. Here is a code example i use:

- (IBAction)dbSizeButton:(id)sender {
    dispatch_queue_t getDbSize = dispatch_queue_create("getDbSize", NULL);
    dispatch_async(getDbSize, ^(void)
    {
        [_dbsizeLable setText:[dbmanager getDbSize]]; 
    });

   dispatch_release(getDbSize);
}

Thank you.

like image 827
Andreas Avatar asked Jun 04 '26 20:06

Andreas


2 Answers

As @MarkGranoff said, all UI needs to be handled on the main thread. You could do it with performSelectorOnMainThread, but with GCD it would be something like this:

- (IBAction)dbSizeButton:(id)sender {

    dispatch_queue_t getDbSize = dispatch_queue_create("getDbSize", NULL);
    dispatch_queue_t main = dispatch_get_main_queue();
    dispatch_async(getDbSize, ^(void)
    {
        dispatch_async(main, ^{ 
            [_dbsizeLable setText:[dbmanager getDbSize]];
        });
    });

    // release
}   
like image 94
ferostar Avatar answered Jun 06 '26 08:06

ferostar


Any UI update must be performed on the main thread. So your code would need to modified to use the main dispatch queue, not a queue of your own creation. Or, any of the performSelectorOnMainThread methods would work as well. (But GCD is the way to go, these days!)

like image 24
Mark Granoff Avatar answered Jun 06 '26 08:06

Mark Granoff