I have a TableView loading a custom cell and loading the data from a JSON string on a server.
The JSON string is parsed to an array of 14 IDs (id_array).
If cell==nil, then I’m using [id_array objectAtIndex:indexPath.row] to get an ID and fetch some more info about for that row from a server, and set up the cell’s labels and image.
When running the app, the UITableView is loading the visible rows [0,1,2,3,4] (cell height is 70px).
When scrolling down the TableView, row [5] is loaded and fetching data from the server, but the problem is that beyond that point – the TableView is repeating those 6 rows instead of requesting new data from the server for the new rows…
But it does request new data for row [5], which is not visible (and not loaded) when the app first runs.
Anyone have any idea why is this happening?
Thanks!
EDIT: Here is my cellForRowAtIndexPath method
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"CustomCell";
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
for (id currentObject in topLevelObjects) {
if ([currentObject isKindOfClass:[UITableViewCell class]]) {
cell = (CustomCell *)currentObject;
NSString *appsURL = [NSString stringWithFormat:@"http://myAPI.com?id=%@",[app_ids objectAtIndex:indexPath.row]];
NSLog(@"row -> %d | id -> %@",indexPath.row,[app_ids objectAtIndex:indexPath.row]);
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:appsURL]];
[cell updateAppInfoForCellWithRequest:request];
break;
}
}
}
// Configure the cell...
return cell;
}
If you are setting data only if
cell==nil, then that is your issue. UITable builds a cache of table view cells, only creating a new one if cell is nil. Therefore, you must set your data each time, i.e. outside of thecell==nilblock.The example below shows that process. First, grab a cell from the pool, if there isn’t a free cell, create a new one. Set the cell’s values for the appropriate row.