Вопрос

I'm having a hard time understanding the following block of code inside cellForRowAtIndexPath:

NSString *uniqueIdentifier = @"SliderCellWithComments";

SliderCellWithComment *cell = nil;

cell = (SliderCellWithComment*) [tableView dequeueReusableCellWithIdentifier:uniqueIdentifier];

if(!cell)
{

    NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"SliderCellWithComment" owner:nil options:nil];
    for (id currentObject in topLevelObjects)
    {
        if([currentObject isKindOfClass:[SliderCellWithComment class]])
        {
            cell = (SliderCellWithComment*)currentObject;
            cell.delegationListener = self; //important!!
            cell.indexPath = [indexPath copy]; //important!!

            break;
        }
    }

    [cell setNameLabelText:@"Days to display:"];
    .
    .
    .

I got this code from StackOverflow and it worked fine until I tried running it on iOS 5.1, where it crashes with an error: 'NSInternalInconsistencyException', reason: 'The NIB data is invalid.'

But what I do not understand about the code is that it doesn't seem to really re-use anything.

For instance: Why does this code assign a value to "cell" twice?

  1. cell=(SliderCellWithComment*)[tableView dequeueReusableCellWithIdentifier:uniqueIdentifier];

  2. cell = (SliderCellWithComment*)currentObject;

If 2 executes, according to me, nothing is being re-used since the cell is assigned a value from new nib.

I don't really get the use of the Array either, why does the following code render blank cells:

static NSString *CellIdentifier = @"SliderCellWithComments";
SliderCellWithComment *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) 
{
    cell = [[SliderCellWithComment alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}

[cell setNameLabelText:@"Days to display:"];
cell.delegationListener = self; //important!!
cell.indexPath = [indexPath copy]; //important!!
.
.
.
Это было полезно?

Решение

Actually the code is reusing cells. [tableView dequeueReusableCellWithIdentifier:uniqueIdentifier]; is asking the table view if he can find a cell with that identifier that can be reuse, if there is a cell that can be reused then the cell will not be nil and the code from the if(!cell){} will not be executed, if the table doesn't find a cell then the if(!cell){} block will be executed and a new custom cell will be created from a xib file.

I don't really get the use of the Array

What you are having there (that array) is a default way of loading a custom view from a xib file.

why does the following code render blank cells

Because in that piece of code you are calling a method from UITableViewCell that is probably not implemented in your custom cell because the custom cell initialization will be done using the xib file (that array that is mentioned in the first quote:)

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top