如何解决这个错误“这个类不是关键的密钥值编码”?

我创build了UITableView并在UITableview每一行都有多个UITextField 。 如何获取每个UITextField值。 以下是我的示例代码。

  - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { int j= 285; for (int i=0; i<7; i++) { NSString *txtIndvalue =[NSString stringWithFormat:@"Index%d",i]; UITextField *txtvalue = [[UITextField alloc] initWithFrame:CGRectMake(j,5.0f,25.0f,20.0f)]; [txtvalue setBorderStyle:UITextBorderStyleLine]; [txtvalue setTag:indexpath.row] [txtvalue setvalue:txtIndvalue forkey:@"test"] [cell addSubview:txtvalue]; j = j + 35; } } error: Terminating app due to uncaught exception 'NSUnknownkeyException' ,reason :'[<UItextField .>' setValue:forUndefindekey:] this class is not key value codeing compliant for the key. Please help me. 

 [txtvalue setvalue:txtIndvalue forkey:@"test"] 

这条线导致崩溃。 setValueForKey不是UITextField的属性/方法。 如果你想在文本框上设置文本,你应该使用

 txt value.text = @"some text". 

如果你想使用KVC for UITextField,试试这个:

 [txtvalue setvalue:txtIndvalue forkey:@"text"]; 

编辑

尝试这个 :

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { int j= 285; for (int i=0; i<7; i++) { NSString *txtIndvalue =[NSString stringWithFormat:@"Index%d",i]; UITextField *txtvalue = [[UITextField alloc] initWithFrame:CGRectMake(j,5.0f,25.0f,20.0f)]; [txtvalue setBorderStyle:UITextBorderStyleLine]; [txtvalue setTag:indexpath.row]; [txtvalue setvalue:txtIndvalue forkey:@"text"]; [cell addSubview:txtvalue]; j = j + 35; } } 

如果您正在使用KVC:

而不是使用[txtvalue setvalue:txtIndvalue forkey:@"text"]; 使用[txtIndvalue setValue:txtIndvalue forKeyPath:@"text"];

更新的代码:

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { int j= 285; for (int i=0; i<7; i++) { NSString *txtIndvalue =[NSString stringWithFormat:@"Index%d",i]; UITextField *txtvalue = [[UITextField alloc] initWithFrame:CGRectMake(j,5.0f,25.0f,20.0f)]; [txtvalue setBorderStyle:UITextBorderStyleLine]; [txtvalue setTag:indexpath.row]; [txtvalue setvalue:txtIndvalue forKeyPath:@"text"]; [cell addSubview:txtvalue]; j = j + 35; } } 

打印KVC的值:

 NSLog(@"%@", [txtvalue valueForKey:@"text"];