Приложение iOS вылетает при удалении последней строки из раздела таблицы - PullRequest
4 голосов
/ 12 марта 2012

Я изучаю редактируемые секционные UITableViews, и у меня возникают проблемы с выяснением причин сбоя моего приложения при удалении последней строки в одном из разделов.Я искал здесь и Google, и мне кажется, что я уже сделал то, что большинство людей решает эту проблему, но не повезло.Я озадачен и благодарен за любую предложенную помощь.

вот мой метод удаления строк таблицы

myTableSections - это NSMutableArray, содержащий NSDictionaries, которые представляют разделы - «Владение» - это ключ, содержащиймассив для строк и ключ "Header" для заголовка раздела

PossessionStore - это синглтон, в котором хранятся все владения для приложения в массиве allPossessions

.allPossessions в NSDictionaries и сохраните их в myTableSections

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{       ////If the table view is asking to commit the delete command
    if (editingStyle == UITableViewCellEditingStyleDelete) {

        // Get the possesion from the row
        Possession *p = [[[myTableSections objectAtIndex:[indexPath section]] objectForKey:@"Possessions"] objectAtIndex:[indexPath row]];

        // delete it from the PossessionStore
        [[[PossessionStore defaultStore] allPossessions] removeObjectIdenticalTo:p];

        // Rebuild myTableViewSections to reflect the data change to the PossessionStore
        [self divideSections];

            // remove the row from the table view with an animation
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }
}

О, да, почти забыл эту последнюю часть - отладочную информацию - на данный момент есть две строки в разделе 1 и одна строка в разделе 2. Затем я удаляю одну строкуиз раздела 1, а затем в последнюю строку из раздела 1. В соответствии с отчетами NSLog, которые я вставил, и сообщением об ошибке, счетчик разделов правильный, как и должно быть в тот момент, но он не показывает, когда раздел удалялся.Если я правильно понимаю ??????????

2012-03-12 00:40:49.938 HomePwnr[53434:f803] commitEditingStyle:forRowAtIndexPath: called
2012-03-12 00:40:49.940 HomePwnr[53434:f803] myTableSections is holding - (
        {
        Header = "Cheap Stuff";
        Possessions =         (
            "Red Car (2U8F9): Worth $20, recorded on 2012-03-12 04:40:38 +0000",
            "Blue Gun (0X2Q7): Worth $14, recorded on 2012-03-12 04:40:40 +0000"
        );
    },
        {
        Header = "Expensive Stuff";
        Possessions =         (
            "Blue Mac (7R3K0): Worth $97, recorded on 2012-03-12 04:40:36 +0000"
        );
    }
)
2012-03-12 00:40:49.942 HomePwnr[53434:f803] divideSections called
2012-03-12 00:40:49.944 HomePwnr[53434:f803]  End of divideSections myTableSections is holding - (
        {
        Header = "Cheap Stuff";
        Possessions =         (
            "Red Car (2U8F9): Worth $20, recorded on 2012-03-12 04:40:38 +0000"
        );
    },
        {
        Header = "Expensive Stuff";
        Possessions =         (
            "Blue Mac (7R3K0): Worth $97, recorded on 2012-03-12 04:40:36 +0000"
        );
    }
)
2012-03-12 00:40:49.946 HomePwnr[53434:f803] returning number of sections: 2
2012-03-12 00:40:49.947 HomePwnr[53434:f803] returning number of sections: 2
2012-03-12 00:40:49.949 HomePwnr[53434:f803] tableView:titleForHeaderInSectionCalled - section = 0
2012-03-12 00:40:49.951 HomePwnr[53434:f803] tableView:titleForHeaderInSectionCalled - section = 0
2012-03-12 00:40:49.953 HomePwnr[53434:f803] tableView:numberOfRowsInSection called for section 0, returning - 1
2012-03-12 00:40:49.954 HomePwnr[53434:f803] tableView:titleForHeaderInSectionCalled - section = 1
2012-03-12 00:40:49.956 HomePwnr[53434:f803] tableView:titleForHeaderInSectionCalled - section = 1
2012-03-12 00:40:49.957 HomePwnr[53434:f803] tableView:numberOfRowsInSection called for section 1, returning - 1
2012-03-12 00:41:32.232 HomePwnr[53434:f803] commitEditingStyle:forRowAtIndexPath: called
2012-03-12 00:41:32.234 HomePwnr[53434:f803] myTableSections is holding - (
        {
        Header = "Cheap Stuff";
        Possessions =         (
            "Red Car (2U8F9): Worth $20, recorded on 2012-03-12 04:40:38 +0000"
        );
    },
        {
        Header = "Expensive Stuff";
        Possessions =         (
            "Blue Mac (7R3K0): Worth $97, recorded on 2012-03-12 04:40:36 +0000"
        );
    }
)
2012-03-12 00:41:32.236 HomePwnr[53434:f803] divideSections called
2012-03-12 00:41:32.238 HomePwnr[53434:f803]  End of divideSections myTableSections is holding - (
        {
        Header = "Expensive Stuff";
        Possessions =         (
            "Blue Mac (7R3K0): Worth $97, recorded on 2012-03-12 04:40:36 +0000"
        );
    }
)
2012-03-12 00:41:32.239 HomePwnr[53434:f803] returning number of sections: 1
2012-03-12 00:41:32.241 HomePwnr[53434:f803] returning number of sections: 1
2012-03-12 00:41:32.242 HomePwnr[53434:f803] tableView:titleForHeaderInSectionCalled - section = 0
2012-03-12 00:41:32.244 HomePwnr[53434:f803] tableView:titleForHeaderInSectionCalled - section = 0
2012-03-12 00:41:32.246 HomePwnr[53434:f803] tableView:numberOfRowsInSection called for section 0, returning - 1
2012-03-12 00:41:32.248 HomePwnr[53434:f803] *** Assertion failure in -[UITableView _endCellAnimationsWithContext:], /SourceCache/UIKit_Sim/UIKit-1914.84/UITableView.m:1021
2012-03-12 00:41:32.250 HomePwnr[53434:f803] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of sections.  The number of sections contained in the table view after the update (1) must be equal to the number of sections contained in the table view before the update (2), plus or minus the number of sections inserted or deleted (0 inserted, 0 deleted).'
*** First throw call stack:
(0x13cc022 0x155dcd6 0x1374a48 0x9ad2cb 0x9b103 0xa66d2 0xa674d 0x3409 0xb26e2 0x208e6b 0x13cde99 0x1914e 0x190e6 0xbfade 0xbffa7 0xbf266 0x3e3c0 0x3e5e6 0x24dc4 0x18634 0x12b6ef5 0x13a0195 0x1304ff2 0x13038da 0x1302d84 0x1302c9b 0x12b57d8 0x12b588a 0x16626 0x20dc 0x2085)
terminate called throwing an exception(lldb) 

Ответы [ 2 ]

9 голосов
/ 12 марта 2012

Все разделы UITableview должны иметь хотя бы одну строку.

Поэтому, если вы хотите удалить последнюю строку, вместо этого необходимо удалить раздел:

 [tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationFade];

Убедитесь, чтоваши данные правильно обрабатывают пустые разделы (при указании количества разделов и т. д.)

8 голосов
/ 12 марта 2012

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

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{       ////If the table view is asking to commit the delete command
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        BOOL lastRow = FALSE;
        if ([tableView numberOfRowsInSection:[indexPath section]] == 1 ) {
            lastRow = TRUE;
        }       
        // Get the possesion from the row
        Possession *p = [[[myTableSections objectAtIndex:[indexPath section]] objectForKey:@"Possessions"] objectAtIndex:[indexPath row]];

        // delete it from the PossessionStore
        [[[PossessionStore defaultStore] allPossessions] removeObjectIdenticalTo:p];

        // Rebuild myTableViewSections to reflect the data change to the PossessionStore
        [self divideSections];

            // remove the row or section if last row from the table view with an animation
        if (lastRow) {
            // NSLog(@"Should be deleting section");
            [tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:YES];
        } else {
            // NSLog(@"Should be deleting row");
            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...