UITableView dequeueReusableCellWithIdentifier Theory

北城以北 提交于 2019-11-27 00:26:43
Jerry Jones

dequeueReusableCellWithIdentifier: only returns a cell if it has been marked as ready for reuse. This is why in almost every cellForRowAtIndexPath: method you will see something like



UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (nil == cell) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                   reuseIdentifier:CellIdentifier];
}

// Do something to cell

return cell;

In effect, enough rows will be allocated to fill the visible part of the tableview (plus one or two more). As cells scroll off screen, they are removed from the table and marked as ready for reuse. As the queue of "available cells" grows, your line that asks for a dequeued cell will start obtaining a cell to use, at which point you will not have to allocate anymore.

The code for deqeueueReusableCellsWithIdentifier: will look something like this:

(Taken from one of my own projects where I do something similar with views/pages in a paged scroll view)

- (UIView*) dequeueReusablePage
{
    UIView* page = [reusablePages_ anyObject];
    if (page != nil) {
        [[page retain] autorelease];
        [reusablePages_ removeObject: page];
    }
    return page;
}

So it keeps a simple NSMutableSet with reusable objects.

When cells scroll off the screen and are not longer visible, they are put in this set.

So you start with an empty set and the set will only grow if you actually have more data to show then is visible on the screen.

Used cell scrolls off the top of the screen, is put in the set, then taken for the cell that appears at the bottom of the screen.

The purpose of dequeueReusableCellWithIdentifier is to use less memory. if we use 100 cells in a tableView then need to create 100 cells every time.It reduce the app functionality and may cause crash. For that dequeueReusableCellWithIdentifier initialise the particular number of cells that we created and the cells will use again for further processing.

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *TableIdentifier = @"YourCellIdentifier";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:TableIdentifier];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TableIdentifier];
    }

    ExternalClassTableViewCell *myCell = [[ExternalClassTableViewCell alloc]init];
    myCell.MyCellText.text = [tableData objectAtIndex:indexPath.row];
    myCell.MyCellImage.backgroundColor = [UIColor blueColor];

    return cell;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!