当我尝试通过标记获取textfield的值时,应用程序崩溃

时间:2014-03-21 17:47:13

标签: ios objective-c cocoa-touch uitextfield

我正在动态地将文本字段添加到我的应用中,但是当我尝试通过这样的标记访问它们时:

UITextField *textField = (UITextField *)[self.view viewWithTag:0];

然后尝试获取值:

NSString *val = textField.text;

应用程序崩溃,我收到此错误:

-[UIView text]: unrecognized selector sent to instance 0x1edb0c30

非常感谢有关如何解决此问题的任何帮助

2 个答案:

答案 0 :(得分:5)

默认tag值为0.因此,[self.view viewWithTag:0];这里您可以收到一个非UITextField的视图而不响应text

您可以使用

检查对象的类
[your_object isMemberOfClass:[UITextField class]];

答案 1 :(得分:0)

我会比有些人说的更进一步,而不是使用标签,你可以参考你的特定文本域:

// Create an array to hold your textfields
NSMutableArray *textFields = [NSMutableArray array]

// Create your textfields and add them to the array
UITextField *textField;
for (NSUInteger idx = 0: idx++; idx < numberOfTextFieldsYouWant) {
    textField = [UITextField alloc] initWithFrame:<whateverYouWant>];
    [textFields addObject:textField];
}

由于您要将对象添加到数组中,而不是使用标记值0,1,2 ......您只需通过数组中的索引访问它

所以而不是

UITextField *textField = (UITextField *)[self.view viewWithTag:0];

你可以写:

UITextField *textField = [textFields objectAtIndex:0];

它更清晰,不依赖于魔术标签,并且您拥有一系列可以删除或在一个地方更改的动态文本字段。