Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C- Trouble updating UI on main thread

I am having some trouble updating my UI using performSelectorOnMainThread. Here is my situation. In my viewDidLoad I set up an activity indicator and a label. Then I call a selector to retrieve some data from a server. Then I call a selector to update the UI after a delay. Here's the code:

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.reloadSchools = [[UIAlertView alloc] init];
    self.reloadSchools.message = @"There was an error loading the schools. Please try again.";
    self.reloadSchools.title = @"We're Sorry";
    self.schoolPickerLabel = [[UILabel alloc]init];
    self.schoolPicker = [[UIPickerView alloc] init];
    self.schoolPicker.delegate = self;
    self.schoolPicker.dataSource = self;
    self.server = [[Server alloc]init];
    schoolList = NO;

    _activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    [self.view addSubview:_activityIndicator];
    [self.view bringSubviewToFront:_activityIndicator];
    [_activityIndicator startAnimating];

    [NSThread detachNewThreadSelector: @selector(getSchoolList) toTarget: self withObject: nil];
    [self performSelector:@selector(updateUI) withObject:nil afterDelay:20.0];
}

The selector updateUI checks to see if the data was retrieved, and calls a selector on the main thread to update the UI accordingly. Here is the code for these parts:

-(void)updateUI
{
    self.schools = [_server returnData];
    if(!(self.schools == nil)) {
        [self performSelectorOnMainThread:@selector(fillPickerView) withObject:nil waitUntilDone:YES];
    }
    else {
        [self performSelectorOnMainThread:@selector(showError) withObject:nil waitUntilDone:YES];
    }
}

-(void)showError {
    NSLog(@"show error");
    [_activityIndicator stopAnimating];
    [self.reloadSchools show];
    }
-(void)fillPickerView {
     NSLog(@"fill picker view");
     schoolList = YES;
     NSString *schoolString = [[NSString alloc] initWithData:self.schools encoding:NSUTF8StringEncoding];
     self.schoolPickerLabel.text  = @"Please select your school:";
     self.shoolArray = [[schoolString componentsSeparatedByString:@"#"] mutableCopy];
     [self.schoolPicker reloadAllComponents];
     [_activityIndicator stopAnimating];
}

When the selector fillPickerView is called the activity indicator keeps spinning, the label text doesn't change, and the picker view doesn't reload its content. Can someone explain to me why the method I am using isn't working to update my ui on the main thread?

like image 787
angerboy Avatar asked Dec 15 '13 03:12

angerboy


1 Answers

dispatch_async(dispatch_get_global_queue(0, 0), ^{
 //load your data here.
 dispatch_async(dispatch_get_main_queue(), ^{
                //update UI in main thread.
            });
});
like image 164
johnMa Avatar answered Oct 19 '22 02:10

johnMa