Question

I have a UITableView which shows file names. When the user taps on the cell, I download the tapped file. For this, I am showing an activity indicator at the left side of a selected cell. After the download ends, the activity indicator will hide. (Remember, the other content in cell wont change).

There is no rule here to click only one cell at a time. The user may tap any number of cells to initiate the download process. I just start the download process and will add it in the operation queue.

Problem: My problem is, consider the scenario where the user taps 3 cells. So three cells will show activity indicator to represent their download processes. If the user scrolls the table view and comes back to the same cells, the activity indicators was hidden. This is because, the tableview's cell creation method will called only for visible cells. So, how can I store the state of each cell's activity indicator?

Was it helpful?

Solution

You can store which file is downloading. And for each row create activity indicator. Something like this:

NSArray* filesArr;

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString* identifier = @"identifier";
    YoursTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if(!cell){
        cell = [[YoursTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    //.....
    if(filesArr[indexPath.row].downloading)
        [cell.activity startAnimating];
    else
        [cell.activity stopAnimating];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(filesArr[indexPath.row].downloading)
         return;
    [self startDownload:filesArr[indexPath.row]];
    filesArr[indexPath.row].downloading = YES;
    [tableView reloadData];
}

OTHER TIPS

As you allude in your question, the issue is in part an artifact of cell reuse. When a cell is dequeued, you must update its activity state on the cell, either by creating a property on the file object for downloading status as Sk0prion suggested, or by some parallel structure.

I would just mention an alternative. If you have only a few cells, you could conceivably bypass cell reuse and store the cells in a dictionary. By avoiding cell reuse, the status in essence, is borne by the cell rather than the object it references. Memory pressure is obviously at issue. I've rarely found a case where this is the preferred solution.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top