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,所以这么明显的提示,你还担心什么?