码迷,mamicode.com
首页 > 其他好文 > 详细

删除cell最后一行时候报错 的解决方案

时间:2015-03-18 16:11:14      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:

由于项目需要,做一个UITableView来实现删除功能。

效果如图:

技术分享

功能思路其实不难:

交代一下,我自己要实现的效果:

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.灵感!源于专注!

希望对你有所帮助!


删除cell最后一行时候报错 的解决方案

标签:

原文地址:http://my.oschina.net/SA03/blog/388294

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!