Search code examples
iosobjective-cuitableviewreloaddata

Problems reloading data in a tableView


I am trying to reload data in a tableview based on a users account permissions whenever they log in.

The two classes involved in this are:

mainViewController and menuViewController

Currently I am able to use

[self.tableView reloadData];

To reload the data when called within the viewWillAppear method. Which is no good for me since the user hasn't logged in when the view loads so there is no data to populate the table at this point.

I have created a method called populateTable in menuViewController.h which I am calling in the mainViewController.m file on button press using the following;

(IBAction)Reload:(id)sender { 
menuViewController *mvc = [[menuViewController alloc]init];
[mvc populateTable];
}

This seems to work correctly as I have an NSLog within the populateTable method which executes. However the reloadData does not work.

Here is my populateTable method;

-(void)populateTable {
self.section1 = [NSMutableArray arrayWithObjects:@"test settings", @"test",           @"test",@"Users and access",@"No-track IPs", nil];
self.section2 = [NSMutableArray arrayWithObjects:@"Rules",     @"Channels",@"Goals",@"Pages", nil];
self.menu = [NSMutableArray arrayWithObjects:self.section1, self.section2, nil];
[self.tableView reloadData];
NSLog(@"Reloading data");
}

Can you guys help me out here, I have been staring at this all day and getting nowhere, thanks!


Solution

  • From my experience this is likely a problem with timing - the IBOutlet of self.tableView is not ready when you call reloadData on it (add an NSLog and see for yourself - it is nil when called).

    To solve this, the populateTable method must be called within the UIViewController's viewDidLoad method. This guarantees that the outlets are not nil and that everything is ready for your data population.

    Also, you should not instantiate your MenuViewController with [[MenuViewController alloc] init] but using the storyboard's instantiateViewControllerWithIdentifier.