2012-03-12 4 views
4

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

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

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

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

ГЗС к divideSections является метод сортировки allPossessions Into 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, которые я вставляю, и сообщение об ошибке msg, подсчет раздела верен, как и должно быть в этой точке, но он не показывает раздел, который когда-либо удаляется. Если я это правильно понимаю ??????????

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) 
+0

Не могли бы вы опубликовать журнал сбоев, чтобы знать выпуск журнала аварии будет играть важную роль :) – doNotCheckMyBlog

+0

Опубликовано. Благодарю. – vichudson1

+1

Убедитесь, что массив отображает его в переменной. Если это не «NSMutableArray», вы не можете добавить/удалить из него. – JTApps

ответ

8

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

- (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]; 
     } 
    } 
} 
+1

Отлично, это именно то, что я сказал, что вам нужно было сделать в моем ответе. Рад, что это работает! – lnafziger

+0

Да, мне просто нужно отдохнуть и вернуться. Получается очень разочаровывает, когда вы находитесь в этом немного лучше, чем место noob, но все еще много, чтобы учиться, и вы не можете понять, что, по вашему мнению, вам нужно. – vichudson1

+0

Я думаю, вы хотите быть осторожным с параметром withRowAnimation.Это не должно быть ДА или НЕТ, скорее UITableViewRowAnimationNone или другое значение UITableViewRowAnimation. – SAHM

8

Все секции UITableview должны иметь как минимум одну строку.

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

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

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

+0

Я тоже пробовал это. Согласно моим NSLogs в отладчике, все подсчеты разделов обрабатываются соответственно. Мой массив, содержащий разделы, восстанавливается при каждом удалении. Поэтому подсчет разделов и строк всегда должен возвращаться, чтобы отразить текущее состояние myTableSections. Я думаю?????? – vichudson1

+1

В соответствии с журналами (и вашим кодом) раздел никогда не удаляется. Вы должны вызвать deleteSections вместо deleteRowsAtIndexPaths для последней строки раздела. – lnafziger