首页 > iOS 开发中 tableView 的 Cell 出队复用方法有两种, 具体作用有何区别?

iOS 开发中 tableView 的 Cell 出队复用方法有两种, 具体作用有何区别?

- (UITableViewCell *)dequeueReusableCellWithIdentifier:(NSString *)identifier; 

- (UITableViewCell *)dequeueReusableCellWithIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath;

如上面所示, 在 iOS6.0 SDK 中加入了第二个方法, 相对于第一个方法来说, 第二个方法只多出来一个 indexPath 参数, 但是实际应用中两种方法具体有什么区别呢?


我自己目前发现的区别是, 如果使用下面这个方法来注册 Cell 的话, 两个方法都可以正常出队复用.

- (void)registerClass:(nullable Class)cellClass forCellReuseIdentifier:(NSString *)identifier;

但是如果使用下面的if判断语句来自己 alloc&init 一个 Cell 的话, 新的复用的方法就是崩溃, 老的复用方法就没问题.

if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kTestCellID];
    }

所以我比较疑惑, 目前我发现的这个情况来看, 反而好像昂是老方法"兼容性"更高, 但是苹果推出新的方法肯定有理由的, 但是具体有什么优点还是琢磨不透, 希望前辈能指点一下.


你应该想问如下两个方法的区别吧:

    - (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);

注意到老的接口,返回值可以为空。老的写法一般是:

UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"cellIdentifier"];
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellIdentifier"];
    }

而新的接口则不然,调用该方法后不用判空。(当然前提是之前调用过registerClass

UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"cellIdentifier" forIndexPath:indexPath];
【热门文章】
【热门文章】