如何解决这个错误"这个类不是符合键值的键值编码"?

时间:2016-01-21 06:59:59

标签: ios objective-c uitableview

我创建了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.

3 个答案:

答案 0 :(得分:2)

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

此行导致崩溃。 setValueForKey不是UITextField的属性/方法。如果要在文本字段上设置文本,则应使用

txt value.text = @"some text".

答案 1 :(得分:0)

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

[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;
        }
}

答案 2 :(得分:0)

如果您使用的是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"];