简体   繁体   中英

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.

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
}   

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!)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM