2012-04-03 112 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

相關問題