我很难理解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:"];
.
.
.
我从StackOverflow获得了这个代码并且它工作正常,直到我尝试在iOS 5.1上运行它,在那里它崩溃并出现错误:'NSInternalInconsistencyException',原因:'NIB数据无效。'
但我对代码不了解的是它似乎并没有真正重复使用任何东西。
例如: 为什么这段代码会为“cell”分配一次值?
cell =(SliderCellWithComment *)[tableView dequeueReusableCellWithIssntifier:uniqueIdentifier];
cell =(SliderCellWithComment *)currentObject;
如果2执行,根据我的说法,没有任何东西被重新使用,因为从新笔尖分配了一个值。
我也没有真正使用数组,为什么下面的代码会渲染空白单元格:
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!!
.
.
.
答案 0 :(得分:0)
实际上代码正在重复使用单元格。 [tableView dequeueReusableCellWithIdentifier:uniqueIdentifier];
询问表视图是否可以找到具有可重复使用的标识符的单元格,如果有一个可以重用的单元格,那么单元格将不是nil和代码如果表没有找到单元格,则if(!cell){}
将不执行if(!cell){}
块,并且将从xib文件创建新的自定义单元格。
我真的没有使用数组
您在那里(该阵列)是从xib文件加载自定义视图的默认方式。
为什么以下代码会呈现空白单元格
因为在那段代码中你正在从UITableViewCell调用一个可能没有在自定义单元格中实现的方法,因为自定义单元格初始化将使用xib文件完成(第一个引用中提到的那个数组:)< / p>