iOS tableView 注册方式复用cell(新)

iOS 在OC的环境下,一般我们使用tableview的数据源的cellForRowAtIndex..方法中 通过Static标记来复用cell,从而达到tableviewcell复用的效果

#pragma mark tableView数据源方法
//组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return <#number#>;
}
//行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return <#number#>;
}
//cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ID = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
    };

    cell.textLabel.text = [NSString stringWithFormat:@"测试数据%tu",indexPath.row];

    return cell;
}

但是这种情况遇到的问题是:如果cell是用xib写的,并且需要在xib中注册cell的ID等,当项目工程变得很多,cell的xib很多的时候,但凡一个cell不注意,但凡一个cell不好了,但凡一个……就是那么凑巧,就是忘记了在这里写上cell的xib的ID,那么cell没有复用,内存慢慢涨啊涨~

这里写图片描述
如上图中忘记了着这里注册,但是程序不会崩溃。
如何巧妙的避免xib类型cell中这种问题嘞?
我们可以通过提前通过注册cell 的方式,在控制器中注册cell 告诉控制器,提前有了这个cell的ID:
将这个方法写成一个tableviewcell的分类:

#import "UITableViewCell+ZTableViewCell.h"

@implementation UITableViewCell (ZTableViewCell)
/**
 *  获得注册cell
 *
 */
+ (instancetype)zhlLoadRegistCell:(UITableView *)tableView indexPath:(NSIndexPath *)indexPath {
    NSString *cellId = [NSString stringWithUTF8String:object_getClassName([self class])];
    return [tableView dequeueReusableCellWithIdentifier:cellId forIndexPath:indexPath];
}
/**
 *  注册cell
 */
+ (void)zhlRegistCell:(UITableView *)tableView {
    NSString *cellId = [NSString stringWithUTF8String:object_getClassName([self class])];
    [tableView registerNib:[UINib nibWithNibName:cellId bundle:nil] forCellReuseIdentifier:cellId];
}
@end

只是需要在使用的时候 提前通过这个分类注册一个这个cell
如下:
这里写图片描述
使用的时候在tableview的数据源方法中:
这里写图片描述

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ZMsgPKTableViewCell *cell = [ZMsgPKTableViewCell zhlLoadRegistCell:self.tableViewPK indexPath:indexPath];
    return cell;
}

再也不用担心我的tableviewcell不复用的问题啦!

但是,如果我忘记了写注册tableviewcell代码怎么办?

这个问题厉害了,如果忘记了写cell 的注册代码,或者写错了位置?程序直接挂掉诶,够提醒你,这里没有注册过cell,所以这么明显的提示,你还担心什么?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值