iOS Tableview dequeueReusableCellWithIdentifier的兩個(gè)方法的區(qū)別

網(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í)例。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容