Search code examples
iphoneiosobjective-cuiviewcontrollerperformselector

Updating label on the main thread is not working


I'm trying to update a label while different tasks are proceeding. I searched and used different options and endup using this way but it still doesn't work:

[processStatusLable performSelectorOnMainThread:@selector(setText:) withObject:@"Creating your account..." waitUntilDone:NO];
DCConnector *dccon = [DCConnector new];
ContactsConnector *conCon = [ContactsConnector new];

if (![dccon existUsersData]) {
    [dccon saveUsersInformation:device :usDTO];
    //created account

    //get friends -> Server call
    [processStatusLable performSelectorOnMainThread:@selector(setText:) withObject:@"Checking for friends..." waitUntilDone:NO];
    NSMutableArray *array = [conCon getAllContactsOnPhone];
    // save friends
    [processStatusLable performSelectorOnMainThread:@selector(setText:) withObject:@"Saving friends.." waitUntilDone:NO];
    if ([dccon saveContacts:array]) {
        [processStatusLable performSelectorOnMainThread:@selector(setText:) withObject:@"Friends saved successfully.." waitUntilDone:NO];
    }
}

The last performSelector is getting executed (at least I see the label text changed on the view), but all other selectors are not working. Any idea why?

EDIT 1

- (void)updateLabelText:(NSString *)newText {
    processStatusLable.text = newText;
}

Solution

  • we can use the following code to run something on the main thread,

    dispatch_async(dispatch_get_main_queue(), ^{
      //set text label
    });
    

    Using that we can write a method like this,

    - (void)updateLabelText:(NSString *)newText {    
        dispatch_async(dispatch_get_main_queue(), ^{
           processStatusLable.text = newText;
        });   
    }
    

    Finally, you can use change your code this way,

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    
        [self updateLabelText:@"Creating your account..."];
        DCConnector *dccon = [DCConnector new];
        ContactsConnector *conCon = [ContactsConnector new];
    
        if (![dccon existUsersData]) {
            [dccon saveUsersInformation:device :usDTO];
            //created account
    
            //get friends -> Server call
            [self updateLabelText:@"Checking for friends..."];
            NSMutableArray *array = [conCon getAllContactsOnPhone];
            // save friends
            [self updateLabelText:@"Saving friends.."];
            if ([dccon saveContacts:array]) {
            [self updateLabelText:@"Friends saved successfully.."];
            }
        }
    });