How to purge a cached UITableViewCell

2019-02-13 17:29发布

Does anyone have suggestions on how to purge a cached UITableViewCell?

I'd like to cache these cells with reuseIdentifier. However, there are times when I need to delete or modify some of the table rows. I expect to call reloadData after the row changes.

Right now, dequeueReusableCellWithIdentifier always returns the cached(obsolete) entry from before. How do I indicate that the cache is stale and needs to be purged?

8条回答
Bombasti
2楼-- · 2019-02-13 17:56

The old data from previous usage of the cell should be cleared with the message prepareForReuse. When a cell is dequeued this message is sent to the cell before it is returned from dequeueReusableCellWithIdentifier:.

查看更多
你好瞎i
3楼-- · 2019-02-13 18:00

I don't know how to purge the cache, however, I use a workaround how to handle the situation, when the rows need to be changed.

First of all, I don't use static cell identifier. I ask the data object to generate it (pay attention to [myObject signature], it provides a unique string describing all needed properties):

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MyObject *myObject = _dataSource[indexPath.row];
    NSString *cellId = [myObject signature];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
        [myObject configureCell:cell];
    }
    [myObject updateCellWithData:cell];
    return cell;
}

[myObject signature] provides different signatures for different list of properties. So, if my object is changed, I just call [self.tableView reloadData], myObject will provide a new signature, and the table load a new cell for it.

[myObject configureCell:cell] places all needed subviews to the cell.

[myObject updateCellWithData:cell] updates the subviews of the cell with current data.

查看更多
登录 后发表回答