2012-07-21 18 views
0

起初我的表格視圖是空的,然後你可以添加你自己的單元格。當你刪除這些單元格時,一切正常。但是,如果你刪除最後一個單元格,然後我的NSMutableArray中有沒有對象,我在我的控制檯得到這個錯誤(也,我使用的核心數據,以節省電池):當數組爲空時停止Tableview崩潰?

*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[_PFBatchFaultingArray objectAtIndex:]: index (123150308) beyond bounds (1)' 

我也試圖把在這行代碼,但我仍然得到同樣的結果:

//arr is my mutable array 
     if ([arr count] == 0) { 
     NSLog(@"No Cells"); 
    } 

這是我從表視圖中刪除的對象:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    if (editingStyle == UITableViewCellEditingStyleDelete) { 
     [arr removeObjectAtIndex:0]; 
     [context deleteObject:[arr objectAtIndex:0]]; 
     [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
    } 
} 

我將如何解決這個問題?

+0

爲什麼每次在索引0處刪除對象? – SALMAN 2012-07-21 15:25:28

回答

3

好的。

我在代碼中發現了兩個問題。

1-爲什麼要刪除索引0處的每個對象?

2-從陣列[arr removeObjectAtIndex:0];比從索引的相同的數組移除對象之後要傳遞一個目的是核心數據刪除它

[context deleteObject:[arr objectAtIndex:0]]; 

這可能是問題。

這一定會幫助你。

使用此:

[context deleteObject:[arr objectAtIndex:indexPath.row]]; 

[arr removeObjectAtIndex:indexPath.row]; 

謝謝:)

+1

非常感謝!你的第二個問題是它!順序錯了,我先把它從數組中取出。我會花幾個小時試圖找出這個問題。再次感謝! – sridvijay 2012-07-21 16:07:43

0

如果你看一下錯誤信息,你的代碼失敗的原因是因爲你的一些代碼正在尋找的123150308一個不存在的指標。如果沒有看到完整的代碼,那是不可能的,但是有一個簡單的解決方法。

解決異常情況爲「預期行爲」的代碼中出現異常問題的好方法是使用@try塊。這是你的tableView@try塊地方:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    if (editingStyle == UITableViewCellEditingStyleDelete) { 
     @try { 
      [arr removeObjectAtIndex:0]; 
      [context deleteObject:[arr objectAtIndex:0]]; 
      [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
     } 
     @catch (NSRangeException *exception) { 
      // Something was out of range; put your code to handle this case here 
     } 
    } 
} 

然而,如果沒有您的應用程序的其它部分的情況下,這是不可能告訴,如果這是錯誤。如果你嘗試這樣做並且它不起作用,那麼錯誤在你的應用程序中更深

+2

捕捉異常通常是**錯誤的方式來處理可可中的錯誤。例外的目的是顯示*程序員錯誤*,這是你應該修復,不抓住。它們可以用於調試錯誤,但不應該在生產代碼中使用這種情況。 – jbrennan 2012-07-21 15:32:57