iOS-分組UITableView刪除崩潰問題(當刪除section中最后一條數據崩潰的情況)


錯誤: 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).

功能思路其實不難,交代一下,我自己要實現的效果:
1.TableView是分組的。
2.點擊刪除按鈕后,某行被刪除。
 
寫完大概功能,運行之后,出現:
 

*** Assertion failure in -[UITableView _endCellAnimationsWithContext:], /SourceCache/UIKit_Sim/UIKit-2372/UITableView.m:1070

libc++abi.dylib: handler threw exception

 
原因:
1.在調用deleteRowsAtIndexPaths:方法前,要確保數據為最新。也就是說,先將要刪除的數據從數據源中刪除。
 
2.分組和分組中行數是變動的,不能寫成死的!
 
3.如果是分組,你會發現很怪的現象:當一個分組中,有多條數據時,你刪除其中一條,正確;當一個分組中,你要刪除唯一的一條時,仍然會報出如上的錯誤!
 
本人,就是百思不得其解。反復調試,數據已經保持最新了的。
 
在網上搜了很多,卻沒有滿意答案。
 
靈感閃過!~~~~
 
刪除某個分組中的最后一條數據時,分組數,和行數都要變。這時候,只調用了deleteRowsAtIndexPaths方法。也就是說,只對行數進行了操作,但是沒有對變動的分組進行操作!
查看幫助API,找到這么一個方法:deleteSections:方法!
加上去,在刪除某個分組中最后一條記錄時,將該分組也刪除!
 
搞定!搞定!
 
最后,貼一下,實現的關鍵思路:
 
1.計算分組數。
 

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

    return [_arrKeys count];// _arrKeys中存放分組

}

 
2.計算每個分組中的個數。
 

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

    

    NSString* _date = [_arrKeys objectAtIndex:section];

    NSArray* _notifications = [_dictData objectForKey:_date];// _dictData存放數據

    return [_notifications count];

 

}

 
3.添加刪除功能的代理方法(核心代碼)。
 

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

{

    if (editingStyle == UITableViewCellEditingStyleDelete) {

 

        [self refreshData];// 刷新_arrKeys和_dictData中的數據

        int newCount=0;

        if (indexPath.section<[_arrKeys count]) {

            NSString *_date = [_arrKeys objectAtIndex:indexPath.section];

            NSArray* _notifications = [_dictData objectForKey:_date];// _dictData存放數據

            newCount= [_notifications count];

        }

        

        [tableView beginUpdates];

        if (newCount<=0) {

            [tableView deleteSections:[NSIndexSetindexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationLeft];

        }

        

        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]withRowAnimation:UITableViewRowAnimationLeft];

        [tableView endUpdates];

        

        

        

    }

    else if (editingStyle == UITableViewCellEditingStyleInsert) {

        // 修改時

    }   

}

 
實現效果圖:
 
總結:
1.遇到問題,查百度,谷歌!
2.先不忙寫,做些小的Demo,搞清楚問題出在那里!
3.看蘋果API(會告訴我們很多機制,原理性的東西)!
4.靈感!源於專注!
希望對你有所幫助!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM