serhat sezer
serhat sezer

Reputation: 1344

UITableview delegate and datasource called twice

I struggle with tableview datasource and delegate methods. I've a tableview if user navigate to that table view controller I'm calling web service method which is block based service after the request finished successfully reloaded tableview sections but tableView:cellForRowAtIndexPath:indexPath called twice. Here's my code.

viewDidLoad

[[NetworkManager sharedInstance].webService getValues:self.currentId completion:^(NSArray *result, BOOL handleError, NSError *error) {

    self.data = result[0];

    dispatch_async(dispatch_get_main_queue(), ^{

        [self.tableView reloadSections:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, 4)] withRowAnimation:UITableViewRowAnimationAutomatic];
    });

}

but cellForRowAtIndexPath self.data value is null in the first time.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
      NSLog(@"%@", self.data); // first time it print null 
}

So is there any ideas about this? Thank you so much!

Upvotes: 1

Views: 1988

Answers (3)

Kex
Kex

Reputation: 8609

Did you initialise the data array in viewDidLoad? If you didn't it will return null.

if you want to avoid two calls to the tableview try this:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    if(!data)
        return 0;

    return yourNumberOfSections;
}

Upvotes: 4

davbryn
davbryn

Reputation: 7176

The tableview calls cellForRowAtIndexPath when it needs to render a cell on screen. If the tableview appears before it has any data, self.data will be empty.

In viewDidLoad set [[self.data = NSMutableArray alloc] init] (for example) and in the datasource/delegate methods of UIITableView it should correctly return numberOfRows etc as zero until your web service populates your data.

Upvotes: 1

Caleb
Caleb

Reputation: 125007

It sounds like -tableView:cellForRowAtIndexPath: is being called simply because the view is loaded and the table is trying to populate itself before you've received any data from your web service. At that point, you won't have set self.data (whatever that is) to any useful value, so you get null instead. When your web service returns some data, the completion routine causes the relevant sections to be reloaded, and the table draws the data.

Upvotes: 0

Related Questions