StackOverFlow链接
方法名介绍
- (nullable __kindof UITableViewCell *)dequeueReusableCellWithIdentifier:(NSString *)identifier; // Used by the delegate to acquire an already allocated cell, in lieu of allocating a new one.
- (__kindof UITableViewCell *)dequeueReusableCellWithIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(6_0); // newer dequeue method guarantees a cell is returned and resized properly, assuming identifier is registered
区别
这两个方法都是在tableView:cellForRowAtIndexPath
这个方法里面获取cell用的
1.对于dequeueReusableCellWithIdentifier:forIndexPath
如果没有给复用的id注册一个class或者nib的话,那么程序就会crash
2.对于dequeueReusableCellWithIdentifier
如果没有给复用id注册一个class或者nib的话,那么就会返回nil
因此对于老的方法
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:identifier];
// 需要手动判断是否为nil
if (cell == nil) {
//创建cell
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}
对于新的方法
dequeueReusableCellWithIdentifier:forIndexPath
//第一步 注册 一个通过xib 一个通过class。随便选一个
- (void)registerNib:(UINib *)nib forCellReuseIdentifier:(NSString *)identifier NS_AVAILABLE_IOS(5_0);
- (void)registerClass:(Class)cellClass forCellReuseIdentifier:(NSString *)identifier NS_AVAILABLE_IOS(6_0);
//第二步
// 不需要判断cell是否为nil,该新方法如果找不到cell,会自动调用
// initWithStyle:withReuseableCellIdentifier 创建一个新的
// 因此,必定不为空
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentify forIndexPath:indexPath];
// 那么参数indexpath有什么用?
// 因为在返回cell之前,会调用委托ableView:heightForRowAtIndexPath来确定cell尺寸(如果已经定义该函数)。
1.The most important difference is that the forIndexPath: version asserts (crashes) if you didn’t register a class or nib for the identifier. The older (non-forIndexPath:) version returns nil in that case.
2.the (then-new) forIndexPath: version starting around 8m30s. It says that “you will always get an initialized cell” (without mentioning that it will crash if you didn’t register a class or nib).
3.The video also says that “it will be the right size for that index path”. Presumably this means that it will set the cell’s size before returning it, by looking at the table view’s own width and calling your delegate’s tableView:heightForRowAtIndexPath: method (if defined). This is why it needs the index path.