UITableView с основными данными insertRowsAtIndexPaths вызывает исключение NSInternalInconsistencyException - PullRequest
0 голосов
/ 13 января 2011

В настоящее время я пишу простой пример табличного представления для iPhone, но, судя по всему, не могу понять, почему возникает следующее исключение.

Рабочий процесс выглядит следующим образом: У меня есть UIViewController, к которому я добавляю UIView. Тогда к этому представлению я добавляю программно определенный UITableView

- (id)init{
    [super initWithNibName:nil bundle:nil];

    tableView = [[UITableView alloc] initWithFrame:CGRectMake(20, 180, 280, 180) style:UITableViewStyleGrouped];
    tableView.backgroundColor = [UIColor redColor];
    tableView.delegate = self;

    return self;
}

Как только это будет завершено, я использую UITableViewDelegate и перезаписываю следующий метод, который должен привести к редактированию моей таблицы. Это вызвано кнопкой и методом селектора

- (void)editList:(id)sender{
    [self setEditing:YES animated:YES];
    [editButton addTarget:self action:@selector(doneList:) forControlEvents:UIControlEventTouchUpInside];
    [editButton setBackgroundImage:[UIImage imageNamed:@"ApplyChanges.png"] forState:UIControlStateNormal];
}

Существует еще один метод doneList, который запускается по завершении, но код не заходит так далеко. Поэтому после нажатия кнопки вызывается мой делегат setEditing и выдается ошибка.

Вот метод делегата

- (void)setEditing:(BOOL)flag animated:(BOOL)animated {
    NSLog(@"setEditing");
    // Always call super implementation of this method, it needs to do some work
    [super setEditing:flag animated:animated];
    // We need to insert/remove a new row in to table view to say "Add New Item..."
    if (flag) {
        // If entering edit mode, we add another row to our table view
        int count = entries.count;
        NSLog(@"int: %i", count);
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:count inSection:0];
        [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];    
    } else {
        // If leaving edit mode, we remove last row from table view
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[entries count] inSection:0];
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationRight];
    }
}

Несколько вещей об этом фрагменте кода во время выполнения: 1) Первоначально массив "records" пуст, поэтому счетчик равен 0, что, по-видимому, возвращает ненулевой объект indexPath 2) Когда записи заполнены фиктивными данными, счет увеличивается правильно, но ошибка все еще происходит 3) Я попытался удалить вызов super setEditing, и по-прежнему возникает ошибка

И, наконец, ошибка.

2011-01-12 16:46:13.623 Book[6256:40b] numberOfRowsInSection
2011-01-12 16:46:13.625 Book[6256:40b] numberOfRowsInSection
2011-01-12 16:46:17.658 Book[6256:40b] setEditing
2011-01-12 16:46:17.659 Book[6256:40b] int: 0
2011-01-12 16:46:17.660 Book[6256:40b] *** Assertion failure in -[UITableView _endCellAnimationsWithContext:], /SourceCache/UIKit_Sim/UIKit-1447.6.4/UITableView.m:976
2011-01-12 16:46:17.692 Book[6256:40b] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0.  The number of rows contained in an existing section after the update (0) must be equal to the number of rows contained in that section before the update (0), plus or minus the number of rows inserted or deleted from that section (1 inserted, 0 deleted).'

Пожалуйста, дайте мне знать, если есть что-то очевидное, чего мне не хватает, возможно, мне нужно включить другой метод делегата, о котором я не знаю?

1 Ответ

0 голосов
/ 13 января 2011

Хорошо, разобрались, ребята.Похоже, что при использовании пользовательского UIViewController, который устанавливает UITableViewDelegate, вам также необходимо иметь набор UITableViewDataSource и указать tableViews dataSource на self.

Пример кода.

Старый код

// Header File 

@interface MyViewController : UIViewController <UITableViewDelegate> {

}

// Main File

- (id)init{
    [super initWithNibName:nil bundle:nil];

    tableView = [[UITableView alloc] initWithFrame:CGRectMake(20, 180, 280, 180) style:UITableViewStyleGrouped];
    tableView.backgroundColor = [UIColor redColor];
    tableView.delegate = self;

    return self;
}

Обновлен рабочий код

// Header File 

@interface MyViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> {

}

// Main File

- (id)init{
    [super initWithNibName:nil bundle:nil];

    tableView = [[UITableView alloc] initWithFrame:CGRectMake(20, 180, 280, 180) style:UITableViewStyleGrouped];
    tableView.backgroundColor = [UIColor redColor];
    tableView.delegate = self;
    tableView.dataSource = self;

    return self;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...