我在Swift iOS應用程序中有一個tableView,允許用戶重新排序行。點擊一個編輯按鈕,可以重新排序或刪除行,然後重新點擊編輯按鈕(現在讀取完成)以完成該過程。在使用tableView之後將新訂單保存到核心數據:moveRowAtIndexPath:toIndexPath:方法
如果我只是簡單地使用tableView:moveRowAtIndexPath:toIndexPath:方法,它就像上面描述的那樣工作,並且表格顯示了當Done被點擊時正確地重新排序的行。但是在返回表時,它不記得新的順序,所以我在覈心數據中添加了一個新的「位置」變量(Int),並且我已經根據該表對自己的表進行了排序。
我的問題是,在用戶移動了一行並點擊完成之後,該表立即重新命令它自己回到之前的狀態。因此,在我的代碼可以正確捕獲新訂單並將其重新寫入核心數據之前,它將在覈心數據中使用舊的(原始)位置變量。
有沒有辦法讓這個新訂單在表重新加載之前單擊完成時捕獲?
這裏是我的代碼來處理移動:
func tableView(tableView: UITableView!, moveRowAtIndexPath sourceIndexPath: NSIndexPath!, toIndexPath destinationIndexPath: NSIndexPath!) {
}
這裏是我的代碼做的是按下時調用。我通過我的表,並重新分配在此基礎上的核心數據的人的處境變的每行的新行:
for currentIteration in 0..<tableView.numberOfRowsInSection(0) {
var indexPathForCurrentIteration = NSIndexPath(forRow: currentIteration, inSection: 0)
let personAtCurrentIndexIteration = fetchedResultsController.objectAtIndexPath(indexPathForCurrentIteration) as PersonModel
personAtCurrentIndexIteration.position = indexPathForCurrentIteration.row
println("\(personAtCurrentIndexIteration.name) has a position value of \(personAtCurrentIndexIteration.position)")
(UIApplication.sharedApplication().delegate as AppDelegate).saveContext()
tableView.reloadData();
}
上面按下Done按鈕時被調用,但我也打過電話是內moveRowAtIndexPath方法沒有成功(相同的結果 - 它會在按下Done時重新加載表格的舊順序)。我也試過註釋掉reloadData沒有成功。
我認爲我的問題可能在於上述內容沒有捕獲新的行順序,而是仍舊獲得舊的行順序。如果是這種情況,那麼我不知道讓它「等待」以獲得新的行順序的最簡單方法。
我開始考慮的一個更長的解決方法是捕獲移動行的初始和最終行值,並基於該更新相應地更新剩餘行的值。其中一些代碼在下面,但我停止了,因爲我認爲這可能是一種更聰明的方式。
if((sourceIndexPath.row > indexPathForCurrentIteration.row) && (destinationIndexPath.row > indexPathForCurrentIteration.row)) {
//if the moved row was ahead of this row before AND after the move, do nothing (don't change this row's position value)
//println("\(personAtCurrentIndexIteration.name)'s position was unchnaged")
} else if((sourceIndexPath.row > indexPathForCurrentIteration.row) && (destinationIndexPath.row < indexPathForCurrentIteration.row)) {
//if the moved row was ahead of this row before BUT behind it after the move, then this row's position value needs to be bumped up one number
personAtCurrentIndexIteration.position = indexPathForCurrentIteration.row+1
//Etc...
在此先感謝您提供的任何幫助。
感謝您快速回復Syed,非常感謝。因此,您在控制器的初始視圖上構建本地緩衝區,使用該緩衝區以正確的順序顯示行,然後在進行編輯時更新該緩衝區。我會嘗試這一點,並希望它會允許我點擊完成後顯示新的行順序(然後我會將新訂單寫入核心數據)。 – ScreenWatcher 2015-02-15 16:41:26