2011-03-23 170 views
0

我想使用alertView來警告用戶他們即將刪除一個對象。這裏是我的代碼:UIAlertView刪除核心數據實體

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

if (editingStyle == UITableViewCellEditingStyleDelete) { 

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Caution!" 
                message:@"Are you sure you want to delete this truck?" 
                delegate:self 
              cancelButtonTitle:@"NO" 
              otherButtonTitles:@"YES", nil]; 
    [alert show]; 
    [alert release]; 
} } 

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{ 
    if (buttonIndex == 1) { 
    NSIndexPath *indexPath = [truckTableView indexPathForSelectedRow]; 
    NSManagedObjectContext *moc = [self.fetchedResultsController managedObjectContext]; 
    Truck *truck = [fetchedResultsController objectAtIndexPath:indexPath]; 

    [moc deleteObject:truck]; 

    NSError *error = nil; 
    if (![moc save:&error]) { 

     NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 
     abort(); 
    } 
} 
else { 
}}  

如果我點擊「否」消失,一切正常,警報視圖正確顯示。如果我點擊「是」,應用程序崩潰而沒有日誌報告,只是EXC_BAD_ACCESS。從我研究的內容來看,alertView在刪除對象之前可能會被釋放?這是正確的嗎?如果是這樣,那麼如何保留alertView,直到刪除處理完成爲止? 感謝您的幫助!

回答

0

這很可能是由於[truckTableView indexPathForSelectedRow]爲零而引起的。正因爲如此,卡車也是零。並且當您嘗試刪除「無對象」時deleteObject:會拋出異常

您應該將要刪除的單元格的indexPath保存爲實例變量。

通常EXC_BAD_ACCESS來自訪問一個發佈的對象,但目前還沒有。在顯示完成後釋放警報即可。

+0

謝謝@fluchtpunkt。我不確定我是否按照「保存單元格的索引路徑」作爲伊娃。爲什麼刪除代碼正常工作,直到我嘗試實現alertView? – JohnnyRedTruss 2011-03-23 16:31:41

+0

沒有提示您是否也使用過[truckTableView indexPathForSelectedRow]?使用'indexPathForSelectedRow'進行刪除只能在刪除之前選擇完全相同的單元格時才起作用。 – 2011-03-23 16:35:47

+0

可能是因爲顯示警報視圖時表格視圖失去焦點時,行被取消選中。我會在調試器的行[NSIndexPath * indexPath = [truckTableView indexPathForSelectedRow]]中設置一個斷點;看看這個變量是否爲零。 – 2011-03-23 17:07:12