UITableView regis... dequeueReus

2017-05-08  本文已影响28人  ghost__

关于注册

- (void)registerNib:(nullable UINib *)nib forCellReuseIdentifier:(NSString *)identifier NS_AVAILABLE_IOS(5_0);
- (void)registerClass:(nullable Class)cellClass forCellReuseIdentifier:(NSString *)identifier NS_AVAILABLE_IOS(6_0);

两种方式 xib cellClass

关于缓存提取

- (nullable __kindof UITableViewCell *)dequeueReusableCellWithIdentifier:(NSString *)identifier;  //ios2.0
- (__kindof UITableViewCell *)dequeueReusableCellWithIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(6_0);

两种方式 一个带indesPath 一个不带 比较直观

关于测试

test1 不进行注册

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellId"];//提取方式一
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellId" forIndexPath:indexPath];//提取方式二
    return cell;
}
控制台打印结果:
提取方式一:
cell为nil   报错:未能提取到一个cell
reason: 'UITableView (<UITableView: 0x7f85c3016000; frame = (0 0; 375 667); clipsToBounds = YES; gestureRecognizers = <NSArray: 0x608000240a50>; layer = <CALayer: 0x608000029620>; contentOffset: {0, 0}; contentSize: {375, 440}>) failed to obtain a cell from its dataSource (<ViewController: 0x7f85c1607630>)'
提取方式二:
cell压根没返回  直接报错:让你必须先去注册一个cell
reason: 'unable to dequeue a cell with identifier cellId - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'

解决(不进行提前注册前提):
采用方式一进行提取  可以在后面加上判断cell 是否为nil  然后进行创建   采用方案二 无解
 if (!cell) {
    cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellId"];
 }

test2 进行注册

//[tableV registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cellId"]; //注册
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellId"];//提取方式一
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellId" forIndexPath:indexPath];//提取方式二
    return cell;
}
控制台打印结果:
提取方式一:无报错
提取方式二:无报错
两种提取方式都可以

官方:
regis... 注册一个类用来创建
dequeueReusable... 从缓存中提取一个cell 如果没有 则会以注册的cell为标准创建新的cell 添加到表中 两种提取方式都会这样做

总结:
使用 dequeueReusableCellWithIdentifier:@"cellId" 这种方式提取 要么加判断 要么进行提前注册
使用 dequeueReusableCellWithIdentifier:@"cellId" forIndexPath:indexPath 这种方式提取 只能提前注册

上一篇 下一篇

猜你喜欢

热点阅读