2015-09-06 99 views
0

我使用PFQueryTableViewController與本地數據存儲。我想使用戶從表中刪除對象與此代碼:iOS - PFQueryTableViewController - 刪除行崩潰

// Override to support editing the table view. 
    - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath 
    { 
    if (editingStyle == UITableViewCellEditingStyleDelete) { 
    // Delete the row from the data source 

     PFObject * object = [self.objects objectAtIndex: indexPath.row]; 

     [object deleteInBackgroundWithBlock:^(BOOL succeeded, NSError * error) { 
      [self loadObjects]; 
     }]; 

     [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 

    } 
    else if (editingStyle == UITableViewCellEditingStyleInsert) { 
    // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view 
    } 
    } 

我得到這個 ***終止應用程序由於未捕獲的異常「NSInternalInconsistencyException」,理由是:「無效的更新:行數無效在部分0.更新(2)後現有部分中包含的行數必須等於更新前(2)部分中包含的行數,加上或減去從該部分插入或刪除的行數部分(0插入,1刪除)以及正數或負數移入或移出該部分的行數(移入0,移出0)。'


我想,這是一個PFQueryTableViewController中使用的註釋,但我找不到解決方案。 非常感謝。

回答

0

當你從一個數組刪除對象,你改變你的UITableView

比方說,你開始在一個陣列100個對象叫objectsArray結構。

  • numberOfRowsInSection =返回objectsArray.count(即100)
  • cellsForRowAtIndexPath = 100個細胞,或然而,許多將被重用,以顯示所有100個對象

現在你只是刪除了一些行從UITableView這裏:[tableView deleteRowsAtIndexPaths:....] 所以我們假設你從objectsArray中刪除了3行,這意味着你從UITableView中刪除了有形的行,所以UITableView認爲numberOfRows.. = 100-3。但它沒有,因爲你沒有更新你的數組減去剛剛刪除的那3個對象。

所以,你實際上是重新加載tableView [self loadObjects]之前那些有形的3行被刪除,或可能在你的情況下,因爲inBackground部分。換句話說,在您試圖爲從tableView中刪除的行設置動畫之前,您再次加載objectsArray。這不可能發生得很快,特別是因爲你把它放在一個異步回調中,你可能不應該爲了性能而這樣做。因此,在短期,你需要更新後您的陣列您刪除行,以便numberOfRowsInSection將始終反映對象

的正確數量如果你的數據是敏感的,你需要等待,看是否回調返回成功deleteInBackground那麼你也應該更新你的tableView那裏,因爲你永遠不知道什麼時候該方法會實際完成:

..deleteInBackgroundWithBlock:^(BOOL succeeded, NSError *error) { 
    if (succeeded) { 
     //get main thread 
     [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
     [self loadObjects]; 
    } else { 
     //error in deleting them 
    } 
} 
+0

謝謝你的回答。有了這段代碼,我得到了其他錯誤:***聲明失敗 - [UITableView _endCellAnimationsWithContext:],/SourceCache/UIKit_Sim/UIKit-3347.44.2/UITableView.m:1623我正在調查這個錯誤的含義。你有什麼主意嗎。 –

+0

最後我在這裏找到了解決方案:http://stackoverflow.com/questions/31358082/when-delete-cell-and-self-loadobjects-in-pfquerytableviewcontroller-it-gets-a –

+0

哦拍。對不起,我的意思是改變這一點,但有其他問題跟蹤並忘記回來。抱歉。這個錯誤是給定的 – soulshined