【问题标题】:UITableViewDataSource methodUITableViewDataSource 方法
【发布时间】:2012-08-14 18:24:58
【问题描述】:
这里是 UITableViewDataSource 协议的 CellForRowAtIndexPath 方法。我在一个网站上看到了那个代码。
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *TableIdentifier = @"SimpleTableItem";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:TableIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TableIdentifier];
}
cell.textLabel.text = [playersReady objectAtIndex:indexPath.row];
return cell;
}
我的问题是:
为什么在这里定义 cell 时写成 = [tableView dequeueReusableCellWithIdentifier:TableIdentifier]; ?那是什么意思?如果我评论了该代码,一切都会好起来的。 那是什么代码?嗯...
如果cell 等于TableIdentifier (SimpleTableItem),if 语句中的cell 如何等于nil? 编写该代码的原因是什么?
为什么TableIdentifier 等于SimpleTableItem? 为了什么?
【问题讨论】:
标签:
objective-c
xcode
cocoa-touch
methods
protocols
【解决方案1】:
表格视图只创建那些可以在屏幕上一次显示的单元格。在此系统重新使用单元格以节省内存之后。
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 20;
}
-(UITableViewCell *)tableView:(UITableView *)tableViewL cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableViewL dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
NSLog(@"Cell == nil so create a new cell....");
}else {
NSLog(@"Reuse Cell ");
}
return cell;
}
CellIdentifier 用于识别单元格,例如,如果您在第 12 个单元格的前十个表格上添加标签,则添加一个按钮,当您重用单元格时会出现问题。因此我们需要创建一个不同的单元格以在单元格上添加按钮并给出它是一个标识符字符串。
【解决方案2】:
iPhone 没有太多内存。但即使在现代计算机上,您也不希望为表格中的每个 单元格初始化一个新单元格。那只是浪费内存。因此,Apple 提出了可重复使用电池的想法。您只需初始化几个填满屏幕的单元格(表格视图)。然后,当用户向下滚动时,一些新的单元格将出现在屏幕底部,但同时其他单元格将在屏幕顶部消失。因此,您可以简单地取出这些单元格并重复使用它们。
幸运的是 UITableView 为你管理这个。当您需要在该方法中设置新单元格时,您所要做的就是询问表格视图是否有任何可用的单元格可以重用。如果有可重用的单元格, dequeueReusableCellWithIdentifier: 将返回其中之一。但是如果还没有可用的(通常是当你第一次用初始单元格填充表格视图时)它将返回 nil。因此,您必须测试 cell 是否为 nil,如果是这种情况,您必须从头开始创建一个新的 cell。
在 iOS 6.0 上,有一个新方法 dequeueReusableCellWithIdentifier:forIndexPath: 总是返回一个有效的单元格(如果还没有可重用的单元格,它会为您创建单元格)。