最近在項目開發(fā)的過程中,發(fā)現(xiàn)和同事就關(guān)于UITableViewCell的初始化存在不同之處,在此整理和對比。
不注冊 Cell (iOS 6.0 之前都用這個方法)
TestTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"test"];
if (cell == nil) {
cell = [[TestTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"test"];
}
return cell;
必須加上if cell == nil的判斷
注冊nib文件
UITableViewCell的創(chuàng)建時通過xib文件創(chuàng)建的
需要在tableView初始化的時候registerNib
[tableView registerNib:[UINib nibWithNibName:@"CustomCell" bundle:nil] forCellReuseIdentifier:kCellIdentify];
在cellForRowAtIndexPath里就不需要對cell 是否為空進行判斷
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentify forIndexPath:indexPath];
注冊代碼創(chuàng)建文件
UITableViewCell的創(chuàng)建是通過代碼創(chuàng)建的
[tableView registerClass:[CustomCell class] forCellReuseIdentifier:@"CustomCell"];
同理在cellForRowAtIndexPath 里如下
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentify forIndexPath:indexPath];
兩種 dequeueReusableCellWithIdentifier 區(qū)別
有 forIndexPath 的方法,需配合 registerClass 或 registerNib使用,并且不需要處理cell為nil的情況