Objective C - cellForRowAtIndexPath 单元格从不为零?

Objective C - cellForRowAtIndexPath Cell Never Nil?

我正在使用 QuickBlox 框架构建聊天应用程序。下面是 cellForRowAtIndexPath 代码。

有些事情我只想对每个单元格执行一次(比如下载图片),所以据我所知,我应该添加 if (!cell) 块来执行此操作。

但是,该块从未真正触发,即使是在第一次加载 tableview 时也是如此。为什么会这样?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

   QBChatMessage *message = [[ChatService shared] messagsForDialogId:self.dialog.ID][indexPath.row]; 
   ChatMessageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ChatMessageCellIdentifier];

   if (!cell) {
   // some things I only want to do once here, such as download images. but it never fires
   }

   [cell configureCellWithMessage:message];
   return cell;
}

如果您没有使用 registerClass:forCellReuseIdentifier:.

注册单元格,则对 dequeueReusableCellWithIdentifier: 的调用只会 return nil

删除您对 registerClass:forCellReuseIdentifier: 的使用,然后 dequeueReusableCellWithIdentifier: 可以 return nil 并且您可以创建一个新单元格并在 if 语句中正确初始化它:

if (!cell) {
    cell = [[ChatMessageTableViewCell alloc] init...]; // use proper init method
    // setup cell as needed for first time
}

相反,您可以在 ChatMessageTableViewCell class 的初始化程序中执行一次性操作。这样您就可以保持注册时习惯的行为。