使用UITableView时经常会遇到以下错误让我们措手不及
*** 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'
意思:带有标记的cell,没有经过注册nib、class或是连接到storyboard的特定cell,不能够被重用
终于下决心把它把它封杀
错误的原因一般有以下:
编译设备的系统低于6.0
未使用配套方法
系统里有以下方法
- (id)dequeueReusableCellWithIdentifier:(NSString *)identifier;
// 通过委托调用来获取一个新的cell代替已被分配使用的cell(Used by the delegate to acquire an already allocated cell, in lieu of allocating a new one)
- (id)dequeueReusableCellWithIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPathNS_AVAILABLE_IOS(6_0);
//(这是新的一个重用cell的方法,该方法通过注册可重用标记,来保证cell的可返回及重置大小) newer dequeue method guarantees a cell is returned and resized properly, assuming identifier is registered
- (id)dequeueReusableHeaderFooterViewWithIdentifier:(NSString *)identifierNS_AVAILABLE_IOS(6_0); // like dequeueReusableCellWithIdentifier:, but for headers/footers
// Beginning in iOS 6, clients can register a nib or class for each cell.
// If all reuse identifiers are registered, use the newer -dequeueReusableCellWithIdentifier:forIndexPath: to guarantee that a cell instance is returned.
// Instances returned from the new dequeue method will also be properly sized when they are returned.
(从ios6开始,客户端可以为每个cell注册一个可重用标记,如果所有的可重用标记都被注册,就根据版本情况配套以下方法使用新方法)
- (void)registerNib:(UINib *)nib forCellReuseIdentifier:(NSString *)identifierNS_AVAILABLE_IOS(5_0);
- (void)registerClass:(Class)cellClass forCellReuseIdentifier:(NSString *)identifierNS_AVAILABLE_IOS(6_0);
- (void)registerNib:(UINib *)nib forHeaderFooterViewReuseIdentifier:(NSString *)identifierNS_AVAILABLE_IOS(6_0);
- (void)registerClass:(Class)aClass forHeaderFooterViewReuseIdentifier:(NSString *)identifierNS_AVAILABLE_IOS(6_0);
例如:
- //6.0之前的用法
- /*
- static NSString *CellIdentifier = @"Cell";
- UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
- if (cell == nil) {
- cell.textLabel.text = [NSString stringWithFormat:@"5.0方法 %d", indexPath.row];
- }*/
- //新方法
-
- [self.notNib_tableView registerClass:[MXCustomCell class] forCellReuseIdentifier:CellIdentifier];
- self.notNib_tableView.dataSource = self;
- self.notNib_tableView.delegate = self;
- [self.view addSubview:self.notNib_tableView];
- UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier
- forIndexPath:indexPath];
- //这里做一些cell属性变换,如:
- cell.textLabel.text = [NSString stringWithFormat:@"6.0方法 %d", indexPath.row];
- return cell;