2011-03-06 139 views
0

我是iPhone應用程序開發的新手。所以,請手下留情我:)UITableView刪除行錯誤

我試圖實現從UITableView中刪除一行,當我得到這個錯誤,對此我無法理解爲什麼

Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (6) must be equal to the number of rows contained in that section before the update (4), plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted).' 

這裏是我的代碼刪除項方法

-(void)deleteItem:(NSIndexPath *)path{ 
Item *i = (Item *)[list objectAtIndex:path.row]; 
NSLog(@"Deleting item [%@]", i.iName); 
int ret; 

const char *sql = "delete from items where id = ?;"; 
if (!deleteStmt) 
{ // build update statement 
    if ((ret=sqlite3_prepare_v2(db, sql, -1, &deleteStmt, NULL))!=SQLITE_OK) 
    { 
     NSAssert1(0, @"Error building statement to delete items [%s]", sqlite3_errmsg(db)); 
    } 
} 

// bind values to statement 
NSInteger n = i.iId; 
sqlite3_bind_int(deleteStmt, 1, n); 
// now execute sql statement 
if ((ret=sqlite3_step(deleteStmt)) != SQLITE_DONE) 
{ 
    NSAssert1(0, @"Error deleting item [%s]", sqlite3_errmsg(db)); 
} 

// now reset bound statement to original state 
sqlite3_reset(deleteStmt); 

[list removeObjectAtIndex:path.row]; // remove from table 
[self readTable]; // refresh array 

}

,這是UITableView中的commitediting風格

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

if (editingStyle == UITableViewCellEditingStyleDelete) { 
    [appDelegate deleteItem:indexPath]; 
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
    }  
} 

有人可以告訴我我做錯了什麼。據我所知,該部分中的行數沒有更新。我對嗎 ??

在此先感謝。

+0

當我刪除表中的最後一個元素時,不會出現此異常。 我錯過了什麼? :( – Neelesh 2011-03-06 15:58:01

回答

0

經過一些重新看代碼,想出解決自己。問題出在

readTable() 

舊的數組在讀取之前未被清空。我用

[list removeAllObjects] 

方法來清空它。它終於奏效了。 :)

0

在我的微薄的意見和嘗試相同的事情後,看起來像表仍然認爲行數沒有改變,所以我讓行隱藏,看起來像它爲我工作。

1

由於蘋果的表視圖編程指南中的規定適用於iOS的刪除次序是相關的:

首先從表中刪除的項目; 秒將其從模型中刪除。

所以,你必須切換兩個刪除命令:


[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
[appDelegate deleteItem:indexPath]; 
+0

對不起..它不工作仍:( – Neelesh 2011-03-06 16:52:38

0

我沒有看到[table reloadData];它工作嗎?通常這是必需的。