简体   繁体   中英

UI is not updating on background thread

I am running an update on an Sqlite3 database in the background when the user presses a force update button.

I want to disable the button as to not lock the database and keep the user from pressing it over and over again. Plus I want to show an Activity Indicator. However, the button is not disabling and the activity indicator does not show.

What am I doing wrong?

I hide the activity indicator when the view is loaded.

Built with storyboards:

在此处输入图片说明

View did load

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //other going on

    [self updateUIInterface:false];


}

The method to update the UI

- (void) updateUIInterface : (BOOL) updating {
    if (updating) {
        //Disable buttons and show activity indicator
        self.actLocalDB.hidden = NO;
        [self.actLocalDB startAnimating];


        self.btnSyncLocal.enabled = NO;
         [self.btnSyncLocal setTitle:@"Updating.." forState:UIControlStateDisabled];
        [self.btnSyncLocal setUserInteractionEnabled:NO];

    } else {
        // Enable buttons
        self.actLocalDB.hidden = YES;
        [self.actLocalDB stopAnimating];


        self.btnSyncLocal.enabled = YES;
        [self.btnSyncLocal setTitle:@"Sync Databases" forState:UIControlStateDisabled];
        [self.btnSyncLocal setUserInteractionEnabled:YES];
    }

}

My method to update the DB

- (IBAction)syncLocalDB:(id)sender {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSLog(@"Begin Local DB Sync");
        [self updateUIInterface:true];

    //db stuff goes here


        dispatch_async(dispatch_get_main_queue(), ^{
            //update UI here
            NSLog(@"Done updating local db");
            [self updateUIInterface:false];

        });

    });

}

You can't make UI changes in background threads. All UI operations need to be performed on the main thread. Here is a nice blog post on the topic and a link to the docs .

Just call updateUIInterface Method before entering the GCD-Block.

- (IBAction)syncLocalDB:(id)sender {

   [self updateUIInterface:true];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSLog(@"Begin Local DB Sync");

    //db stuff goes here


        dispatch_async(dispatch_get_main_queue(), ^{
            //update UI here
            NSLog(@"Done updating local db");
            [self updateUIInterface:false];

        });

    });

}

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