user3138007
user3138007

Reputation: 637

Where to insert [tableView reloadData]

I got a global mutable array. When I add objects from an other viewController to it I want the tableView to update. I do know that I have to use [tableView reloadData] to update my tableView. But I have no idea where I should put this piece of code to hold my tableView up to date?

I tried it like this:

 -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    AppDelegate *delegate= (AppDelegate*)[[UIApplication sharedApplication] delegate];

    return [delegate.globalArray count];

    [tableView reloadData];        
}    

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    AppDelegate *delegate= (AppDelegate*)[[UIApplication sharedApplication] delegate];

    UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.textLabel.text = delegate.globalArray [indexPath.row];
    return cell;

    [tableView reloadData];    
}

Upvotes: 0

Views: 312

Answers (2)

Lorenzo B
Lorenzo B

Reputation: 33428

SB. answer is correct. reloadData should be used when the content of your array changes.

To maintain the table updated it strictly depends on your application flow. I'll try to explain.

Suppose for example, when you start the app the table view (managed by a specific controller, say A) is visible and you can add additional elements with a plus button. Tapping on the plus button it will open a modal controller (say B) that lets you to add elements. To communicate from B to A the data reloading, you can use notifications, blocks and so on.

Anyway, as said, it depends on your application. Maybe, if the controller that manages the table is each time a fresh one, you don't need such type of approach...

Upvotes: 0

NG.
NG.

Reputation: 22914

You should call reloadData whenever the contents of your array change. Don't call it in those methods (after a return does nothing - surprised you don't get a compile error about unreachable)

Upvotes: 2

Related Questions