2012-04-03 108 views
1

尝试删除单元时,使用自定义按钮时遇到此错误。使用自定义UIButton删除UITableViewCell

*终止应用程序由于未捕获的异常 'NSRangeException',原因是: '* - [__ NSArrayM removeObjectAtIndex:]:指数1超出范围[0 .. 0]'

继承人如何我代码是结构化的。我有一个自定义UITableViewCell,其中包含一个UIButton,它具有删除单元的操作。删除单元格的操作在我的主视图控制器中,其中包含单元格的实际indexPath。这个结构工作正常。

继承人删除单元格的操作。

NSIndexPath *indexPath = [self globalIndexPath]; 

[self.array removeObjectAtIndex:[indexPath row]]; 
[db deleteTaskAtIndex:[indexPath row]]; 

[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationFade]; 

当我宣布上述indexPath,则globalIndexPath属性设置在我cellForRowAtIndexPath,给它原来indexPath的价值。我就是这么宣布的。

[self setGlobalIndexPath:indexPath]; 

现在,我已经在这里下了一些NSLogs一个有记录的indexPath。例如在viewWillAppear方法和viewDidLoad方法中,都给我准确的indexPath,我甚至检查了array输出,并且它们都返回准确的结果,所以我真的不知道为什么它给了我这个错误。

这是我的自定义单元中的代码,用于检测按钮被点击的时间。

NSArray *notificationArray = [[UIApplication sharedApplication] scheduledLocalNotifications]; 
if (!notificationArray || !notificationArray.count) 
{ 
    [[NSNotificationCenter defaultCenter] postNotificationName:@"DeleteSignal" object:nil]; 
} 
else 
{ 
    UILocalNotification *notif = [notificationArray objectAtIndex:[checkbox tag]]; 
    [[UIApplication sharedApplication] cancelLocalNotification:notif]; 
} 

然后我删除使用NSNotificationCenter用钥匙DeleteSignal细胞。

+0

尝试设置一个断点,当[indexPath行]是> = [self.array计数]之前每个删除...或者声明该行少于count。另外,如果不刷新表格,你有可能删除多个项目? – 2012-04-03 11:16:01

+0

我会尝试断点,但是,我尝试在我的'viewDidLoad'和'viewWillAppear'中重新加载我的'tableView'。 – Souljacker 2012-04-03 11:21:13

+0

我在我的删除函数前后做了一个if语句,并且放了一个日志,但我不知道如何工作。 – Souljacker 2012-04-03 12:00:37

回答

1

如果要设置在cellForRowAtIndexPath(和其他地方)的globalIndexPath,globalIndexpath将永远知道在最后一个单元格,这得到了创建或出队的indexPath,的一个地方,用户可以实际使用的按钮。似乎已经被设计破坏了。或者你的单元格很大,只有一个可见?

起初,我会尝试设置你的细胞UIButton的标签在cellForRowAtIndexPath

myButton.tag = indexPath.row + SOMEOFFSETTOASSUREYOURTAGDOESNTGET0; 

,然后通过这个标签让你的行动indexPath:

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:(UIButton*)sender.tag - OFFSET inSection:0]; 

当然,这只是如果你只有一个部分的作品。如果您需要处理多个部分,则可以使用包含所有indexPath的数组,并将UIButton的标记设置为数组中indexPath的索引。

UPDATE

虽然在技术上是可能的(MIS)使用NSNotificationCenter你在做什么,我真的建议你通过这个tutorial行走。

+0

我的动作是在主视图控制器中,它只是一个简单的'void'。你声明'indexPath'的代码返回一个错误,说发送者是未声明的。它应该是我的按钮? – Souljacker 2012-04-03 13:34:25

+0

您是否定义了一个协议并在自定义的'UITableViewCell'中使用委托来调用该操作? – 2012-04-03 13:42:10

+0

是的,发件人应该是你的UIButton。 – 2012-04-03 13:43:40

相关问题