最近在项目开发的过程中,发现和同事就关于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的创建时通过xib文件创建的
需要在tableView初始化的时候registerNib
[tableView registerNib:[UINib nibWithNibName:@"CustomCell" bundle:nil] forCellReuseIdentifier:kCellIdentify];
在cellForRowAtIndexPath里就不需要对cell 是否为空进行判断
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentify forIndexPath:indexPath];
注册代码创建文件
UITableViewCell的创建是通过代码创建的
[tableView registerClass:[CustomCell class] forCellReuseIdentifier:@"CustomCell"];
同理在cellForRowAtIndexPath 里如下
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentify forIndexPath:indexPath];
两种 dequeueReusableCellWithIdentifier 区别
有 forIndexPath 的方法,需配合 registerClass 或 registerNib使用,并且不需要处理cell为nil的情况