注册可重用单元格
例如:
- (
UITableViewCell
*)tableView:(
UITableView
*)tableView cellForRowAtIndexPath:(
NSIndexPath
*)indexPath{
static NSString *ID = @"cell" ;
SUNWeiboCell *cell = [tableView dequeueReusableCellWithIdentifier :ID];
if (cell == nil ) {
cell = [[ SUNWeiboCell alloc ] initWithStyle : UITableViewCellStyleDefault reuseIdentifier :ID];
}
cell. weiboFrameItem = self . weiboFrames [indexPath. row ];
return cell;
}
1、
如果,没有指定可重用标示符,会出现下面这个错误。
(2)、一旦注册了可重用单元格
[tableView dequeueReusableCellWithIdentifier:ID];
与
[tableView dequeueReusableCellWithIdentifier:ID forIndexPath:indexPath];
方法是等价的
解决方法:
2、运行,如果发现出现下面这种错误,一种情况,就是没有指定自定义的cell
2014
-
10
-
07
01
:
54
:
42.056
新浪微博
[
13343
:
60
b] *** Terminating app due to uncaught exception
'NSInvalidArgumentException'
, reason:
'-[UITableViewCell setWeiboFrameItem:]: unrecognized selector sent to instance 0x8e32910
’
解决方法:
3、如果把上例子中下面三句话注释了,程序也不会报错。
if
(cell ==
nil
) {
cell = [[ SUNWeiboCell alloc ] initWithStyle : UITableViewCellStyleDefault reuseIdentifier :ID];
cell = [[ SUNWeiboCell alloc ] initWithStyle : UITableViewCellStyleDefault reuseIdentifier :ID];
}
原因:
Xcode6规定,在storyboard中指定了可重用标示符,同时指定了自定义cell,系统会为tableView注册一个原形cell,专门用来做可重用单元格,一旦缓冲区不存在可重用单元格,系统会使用原形cell重新实例化一个cell。因此,在storyboard中注册了原形cell,就不需要做cell==nil的操作了。
4.如果使用
[tableView
dequeueReusableCellWithIdentifier
:ID
forIndexPath
:indexPath];这个方法,前提条件是要求一定注册可重用标示符,否则,就会报下面的错误。
2014
-
10
-
07
02
:
14
:
13.512
新浪微博
[
13492
:
60
b] *** Terminating app due to uncaught exception
'NSInternalInconsistencyException'
, reason:
'unable to dequeue a cell with identifier cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard’。
5.注意:
(1)、[tableView dequeueReusableCellWithIdentifier:ID forIndexPath:indexPath];这个方法中的forIndexPath:indexPath的作用:
专门用于检查是否注册了可重用单元格,从而达到简化代码的目的。
(2)、一旦注册了可重用单元格
[tableView dequeueReusableCellWithIdentifier:ID];
与
[tableView dequeueReusableCellWithIdentifier:ID forIndexPath:indexPath];
方法是等价的
(3)、如果把storyboard中tableView系统自带的cell给删掉,那么必须在
- (void)viewDidLoad
{
// 为tableView注册可重用单元格
[self.tableView registerClass:[SUNWeiboCell class] forCellReuseIdentifier:ID];
}
{
// 为tableView注册可重用单元格
[self.tableView registerClass:[SUNWeiboCell class] forCellReuseIdentifier:ID];
}
(4)、在自定义XIB中,不能做tableView的嵌套。