Objective c 如何正确链接自定义UITableViewCell和access元素

Objective c 如何正确链接自定义UITableViewCell和access元素,objective-c,ios,uitableview,Objective C,Ios,Uitableview,我在创建自定义UITableViewCell时遇到了难以置信的困难。我已经彻底检查了stackoverflow和google,但是发布的所有解决方案要么不完整,要么不正确,要么已经足够了 这就是我想做的。我想在自定义单元格中加载MyTableViewController,让我们将它们称为MyCustomCell,而不是默认单元格。我希望MyCustomCell是UITableViewCell的一个完整的子类,因此我有一个.xib,其中只有一个UITableViewCell(以及其中的一些测试标签

我在创建自定义UITableViewCell时遇到了难以置信的困难。我已经彻底检查了stackoverflow和google,但是发布的所有解决方案要么不完整,要么不正确,要么已经足够了

这就是我想做的。我想在自定义单元格中加载MyTableViewController,让我们将它们称为MyCustomCell,而不是默认单元格。我希望MyCustomCell是UITableViewCell的一个完整的子类,因此我有一个.xib,其中只有一个UITableViewCell(以及其中的一些测试标签)。单元格标识符设置为“MyCustomCell”,类设置为“MyCustomCell”。我可以用MyCustomCell.h拖动和链接标签

回到MyTableViewController.m,我有以下代码

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *ident = @"MyCustomCell";

MyCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:ident];//appears to crash here
if(cell == nil){
    NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:ident owner:self options:nil];
    for(id currentObject in topLevelObjects){
        if([currentObject isKindOfClass:[MyCustomCell class]]){
            cell = (MyCustomCell*)currentObject;
            break;
        }
    }
}
cell.myCustomLabel.text = @"hello world";//myCustomLabel from the .xib is linked up to the 
//proper variable in MyCustomCell.h, and it's also being synthesized
//I'd like to modify all the custom labels,imageviews,etc here
return cell;
}
运行此命令会导致以下错误:

Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<MyTableViewController 0x7d5ba80> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key myCustomLabel.'
由于未捕获的异常“NSUnknownKeyException”而终止应用程序,原因:“[setValue:forUndefinedKey:]:此类不符合密钥myCustomLabel的键值编码。”

当我忘记将某个东西与一个.xib和它的.h文件连接时,或者当它没有被合成时,通常会出现这种情况,但我已经检查过了,它似乎成功了。这里有什么我做错的吗?我是否必须执行[[MyCustomCell alloc]init]或[[MyCustomCell alloc]initWithCustomMethod:…]操作?

如果您的目标是iOS 5,请使用以下方法:

 [self.tableView registerNib:[UINib nibWithNibName:@"yourNibName" bundle:nil] forCellReuseIdentifier:@"yourNibIdentifier"];
然后,您只需使用标识符从nib获取单元格

[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

最后:确保您确实为UITableViewCell子类的nib分配了正确的类名和标识符。

您的第一个建议似乎不起作用。我还重新检查了笔尖,一切看起来都应该正常。最后,我删除了所有内容,重新开始,现在看起来所有内容都连接得恰到好处