2011-01-12 2 views
0

Я сейчас в процессе написания простого примера таблицы для iPhone, но для жизни я не могу понять, почему возникает следующее исключение.UITableView с базовыми данными insertRowsAtIndexPaths вызывает NSInternalInconsistencyException

Рабочий процесс выглядит следующим образом: У меня есть 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) Изначально «записи» массив пуст, поэтому отсчет 0, который, кажется, возвращать не нулевой indexPath объект 2) Когда записи заполняются фиктивными данными Счетной увеличивается правильно, но ошибка все равно происходит 3) Я попытался удалить супер вызов 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

Вы уверены, что хотите entries.count, если вы нуля в массиве строк? – joshpaul

ответ

0

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

Пример кода.

Старый код

// 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; 
} 
Смежные вопросы