tableView cellForRowAtIndexPath: runs before ViewDidLoad?

ios, objective-c, uitableview

Solution

I think it's because you are updating the array into block which is running into background and your delegates called, just simply reload your tableView into block completion

[getCartQuery getFirstObjectInBackgroundWithBlock:^(PFObject *currentCartObject, NSError *error) {

        // NSLog([currentCartObject objectId]);

        currentCart = [currentCartObject objectForKey:@"cartContents"];

        dictFoodId = [currentCart valueForKey:@"foodId"];

        dictQty = [currentCart valueForKey:@"qty"];

        [self.tableView reloadData];

    }];

Problem

I am trying to display some arrays in a UITableViewController. I have a custom cell with a NIB. The problem I'm running into is my table rows try to populate before my arrays are loaded in my `ViewDidLoad` . Setting breakpoints show that my table rows are being created and then directly after my arrays are given values (which are set in my `ViewDidLoad`. Can anyone tell me why the `tableView` method is running before the `ViewDidLoad`? What do I need to do to ensure my arrays are loaded before the table rows are populated? Here is my `ViewDidLoad` : ``` - (void)viewDidLoad { [super viewDidLoad]; NSLog(@"go"); PFQuery *getCartQuery = [PFQuery queryWithClassName:@"chwCart"]; [getCartQuery whereKey:@"userId" equalTo:[PFUser currentUser].objectId]; [getCartQuery whereKey:@"status" equalTo:@"open"]; [getCartQuery getFirstObjectInBackgroundWithBlock:^(PFObject *currentCartObject, NSError *error) { // NSLog([currentCartObject objectId]); currentCart = [currentCartObject objectForKey:@"cartContents"]; dictFoodId = [currentCart valueForKey:@"foodId"]; dictQty = [currentCart valueForKey:@"qty"]; }]; NSLog(@"Should be loaded"); [self.tableView registerNib:[UINib nibWithNibName:@"foodCell" bundle:nil] forCellReuseIdentifier:@"foodCell"]; } ``` Here is my `tableView cellForRowAtIndexPath:` ``` (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"foodCell"; foodCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; if (cell == nil) { cell = [[foodCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; } cell.foodTitle.text = [dictQty objectAtIndex:indexPath.row]; return cell; } ```

Original source