[英]Why I use indexPathsForSelectedRows to get all cell selected to delete but crashed my app?
這是我的一些代碼
NSArray *selectedRows = [self.playHistoryTableView indexPathsForSelectedRows];
if (selectedRows.count) {
for (NSIndexPath *selectionIndex in selectedRows)
{
OneSery *sery = [self.playHistoryDic objectAtIndex:selectionIndex.row];
[CoreDataManager deleteOneHistoryBySeryId:sery.seryId andVideoId:sery.latestVideo.videoId];
[self.playHistoryDic removeObjectAtIndex:selectionIndex.row];
}
[self.playHistoryTableView deleteRowsAtIndexPaths:selectedRows withRowAnimation:UITableViewRowAnimationAutomatic];
}
一次選擇一個單元格時,效果很好。 但是,當多選單元格時,它將像這樣崩潰:
Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 1 beyond bounds [0 .. 0]'
我知道這是什么意思,但我不知道我哪里錯了。 我嘗試過,當它具有三個單元格並選擇要刪除的第一個和第二個單元格時,它將刪除第一個和第三個單元格。 當它只有兩個單元格時,我選擇兩個單元格都將其刪除,這會使我的應用程序崩潰。 當我調試它時,甚至Onesery *sery
值也是錯誤的。 那么,在selectedRows是正確的情況下,selectionIndex怎么可能是錯誤的呢?
NSArray *selectedRows = [self.playHistoryTableView indexPathsForSelectedRows];
NSMutableIndexSet *indicesOfItemsToDelete = [[NSMutableIndexSet alloc] init];
if (selectedRows.count) {
for (NSIndexPath *selectionIndex in selectedRows)
{
OneSery *sery = [self.playHistoryDic objectAtIndex:selectionIndex.row];
[CoreDataManager deleteOneHistoryBySeryId:sery.seryId andVideoId:sery.latestVideo.videoId];
[indicesOfItemsToDelete addIndex:selectionIndex.row];
}
[self.playHistoryDic removeObjectsAtIndexes:indicesOfItemsToDelete];
[self.playHistoryTableView deleteRowsAtIndexPaths:selectedRows withRowAnimation:UITableViewRowAnimationAutomatic];
}
在你的循環中
[self.playHistoryDic removeObjectAtIndex:selectionIndex.row];
所以您要更改項目列表。 在每次迭代中,您嘗試訪問一個項目,但是在第一個項目之后,下一個已移動,因為您已刪除了一個項目。 對於隨后的每個項目,情況都會更糟。
最終,您到達嘗試訪問某項的地步,但已刪除了許多項,以至於超出列表末尾,然后崩潰。
您應該在循環中獲取要刪除的項目的數組,並在循環完成后立即將其全部刪除。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.