XCODE TableView с несколькими разделами и делегированным источником данных из массива массивов - не удается удалить строку без ошибки?

У меня есть TableView с несколькими разделами, в котором есть источник данных делегата, который ссылается на массив массивов. Каждый массив в массиве массивов является собственной секцией табличного представления. У меня он загружается правильно и у меня включена кнопка редактирования, но когда я пытаюсь удалить приложение, оно вылетает со следующей ошибкой.

*** Завершение работы приложения из-за необработанного исключения «NSInternalInconsistencyException», причина: «Недопустимое обновление: недопустимое количество разделов. Количество разделов, содержащихся в табличном представлении после обновления (9), должно быть равно количеству разделов, содержащихся в табличном представлении до обновления (10), плюс или минус количество вставленных или удаленных разделов (0 вставленных, 0 удален).'

Теперь я НЕ удаляю раздел, поэтому немного запутался, вот пример моего кода. Я долго искал этот форум, но просто не могу понять, что я сделал не так.

ВОТ МОЙ КОД:

// Calculate how many sections in the table view from the array or arrays

- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{

    AppDelegate *delegate = [[UIApplication sharedApplication]delegate];

    NSInteger sections = [delegate.packing.packingListArray count];

    return sections;
}

// Load the array and extract the count of items for each section

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    // For each array within the array of array count the items
    AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    NSArray *sectionContents = [delegate.packing.packingListArray objectAtIndex:section];
    NSInteger rows = [sectionContents count];

    return rows;
}

// Load the list into the table view

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    // Set the cell identifier - using ID field thats been set in interface builder
    static NSString *CellIdentifier = @"DestinationCell";

    // Re-use existing cell?
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    // If no reusabled cells then create a new one
    if (cell == nil){
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    // Add the relevant packing list array from the array of arrays
    AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    NSArray *sectionContents = [delegate.packing.packingListArray objectAtIndex:[indexPath section]];
    NSString *contentForThisRow = [sectionContents objectAtIndex:[indexPath row]];

    cell.textLabel.text = contentForThisRow;



    // Return the formatted cell with the text it needs to display in the row
    return cell;
}

// Delete row from table and update data source array

- (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle) editingStyle forRowAtIndexPath:(NSIndexPath *) indexPath {

    if (editingStyle ==UITableViewCellEditingStyleDelete) {


        [tableView beginUpdates];

        // Delete the item from the array
        AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
        [delegate.packing.packingListArray  removeObjectAtIndex:indexPath.row];


        // Delete the row from the table view
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

        [tableView endUpdates];

    }


}

У меня есть ощущение, что это как-то связано, возможно, с усложнением массива массивов, создающих несколько разделов, но должен ли быть какой-то способ сделать это?

Любая помощь очень ценится, так как я уже несколько часов смотрю на этот же код.


person Carl Alderton    schedule 21.05.2013    source источник


Ответы (1)


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

AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
[[delegate.packing.packingListArray objectAtIndex:indexPath.section] removeObjectAtIndex:indexPath.row];

Затем у меня возникла проблема с тем, как я определял свои массивы, поскольку они были построены из plist, который, хотя и был установлен как NSMutableArray, но преобразовывался в NSArray. Итак, в конце этого заявления я включил.

........mutablecopy];

Все проблемы решены :)

person Carl Alderton    schedule 22.05.2013