網(wǎng)上版本
帶indexPath的方法總是返回一個(gè)cell(也就是說不可能為空),另一個(gè)方法是有可能為nil的;即:在- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath方法中可以省略以下代碼:
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
自測(cè)版本
- 在iOS9.3和iOS8.1下測(cè)試,只要為tableview注冊(cè)了相應(yīng)的cell類,無論用兩種方法中的哪一種,都不用手動(dòng)創(chuàng)建就能獲得cell,不會(huì)為nil。
- 然而如果沒有為tableview注冊(cè)cell類,則
dequeueReusableCellWithIdentifier:forIndexPath:會(huì)crash,crash原因?yàn)椤癿ust register a nib or a class for the identifier or connect a prototype cell in a storyboard”,即dequeueReusableCellWithIdentifier:forIndexPath:方法必須與register方法配套使用。 - 但如果沒有為tableview注冊(cè)cell類,
dequeueReusableCellWithIdentifier:方法也不會(huì)崩潰,只是會(huì)返回nil,此時(shí)需要我們手動(dòng)創(chuàng)建cell,如果未創(chuàng)建,則程序會(huì)crash,crash原因?yàn)椤癠ITableView failed to obtain a cell from its dataSource”,即此時(shí)tableView無法獲取到cell實(shí)例。