当调用textFieldDidEndEditing时,应用程序会冻结

时间:2015-03-22 20:46:27

标签: ios objective-c uitableview delegates uitextfield

我的自定义UITableView内有UITextFields。在cellForRow...我让textFields代表自我。 (在我的主要VC课程中。)我从textField获取文本的方式是textFieldDidEndEditing,我将其添加到mutableArray

然后,当选择一个按钮时,我会添加不同的单元格ID:

- (IBAction)addRow:(id)sender
{
    NSInteger row = [self.rowArray cound];
    [self.rowArray insertObject:@"anotherCell" atIndex:row];

    NSIndexPath *indexPath = [NSindexPath indexPathForRow:row inSection:0];
    [self.myTableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}

textField中有cellID,我将delegate设置为自我。

textFieldDidEndEditing中,我创建了NSLog textField.text,当该方法从最初的textField调用时,它按预期工作。

但是当textFieldDidEndEditingtextField({1}}(已添加的单元格)的单元格中调用anotherCell时,整个模拟器会冻结。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellID = [self.rowArray objectAtIndex:[indexPath row]];

    customCell *cell = [tableView dequeuereusablecellwithidentifier:cellID forIndexPath:indexPath];

    cell.name.delegate = self; // From cell that is initially there
    cell.phoneNumber.delegate = self; // From the added cell

    return cell;
}

(如果这令人困惑,或者如果您需要更多代码,请在评论中告诉我。谢谢)

修改

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if (textField.tag <= 9)
    {
        NSLog(@"%@", textField.text); // This works
    }

    UIView *superview = textField.superview;
    while (![superview isMemberOfClass:[UITableViewCell class]]) {
        superview = superview.superview;
    }
    CustomCellClass *cell = (CustomCellClass *)superview;
    NSIndexPath *indexPath = [self.myTableView indexPathForCell:cell];

    if (textField.tag >= 12)
    {
        if ([self.inputArray count] > indexPath.row) // So I won't get the error message of [__NSArrayM objectAtIndex:]: index 1 beyond bounds for empty array'
        {
            for (NSUInteger i = [self.inputArray count]; i < indexPath.row; i++) {
                [self.inputArray insertObject:@"" atIndex:i];
                NSLog(@"%lu", (unsigned long)i);
            }
        }

        NSLog(@"%@", self.inputArray);
    }
}

1 个答案:

答案 0 :(得分:2)

你的代码在这里陷入无限循环:

while (![superview isMemberOfClass:[UITableViewCell class]]) {
    superview = superview.superview;
}

因为isMemberOfClass仅在superview类为UITableViewCell时才返回true,但如果它是UITableViewCell子类则不返回true。如果您将isMemberOfClass更改为isKindOfClass,则应该有效。查看Apple文档here