dequeueReusableCellWithIdentifier vs dequeueReusableCellWithIdentifier : forIndexPath

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值