我正在尝试moveRowAtIndexPath
使用Core Data的方法。我的程序是用户驱动的,这意味着用户反复更新数据,并且基本上是一个显示实体名称的表格视图。每个实体都有两个属性:名称和代表其在tableView中位置的整数,我们称它为orderPosition
。我还创建了一个本地变量来存储lastIndex
,这是数组中对象的数量。这使我可以为我创建的每个实体分配索引值(表中的最后一位)。我无法弄清楚的是如何orderPosition
在我的实体中使用存储的属性在View Controller中为tableView创建一个排序数组,以及如何使用它来完成moveRowAtIndexPath
工作。
override func viewWillAppear(animated: Bool) {
let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context = appDelegate.managedObjectContext!
let fetchReq = NSFetchRequest(entityName: "Object")
objectData = context.executeFetchRequest(fetchReq, error: nil)!
lastIndex = objectData.count
tableView.reloadData()
}
override func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
let val: AnyObject = self.objectsData.removeAtIndex(sourceIndexPath.row)
self.objectsData.insert(val, atIndex: destinationIndexPath.row)
let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context = appDelegate.managedObjectContext!
var fetchReq = NSFetchRequest(entityName: "Object")
fetchReq.predicate = NSPredicate(format: "orderPosition = %@", sourceIndexPath.row)
if let fetchResults = appDelegate.managedObjectContext!.executeFetchRequest(fetchReq, error: nil) as? [NSManagedObject] {
if fetchResults.count != 0{
var managedObject = fetchResults[0]
managedObject.setValue(destinationIndexPath.row, forKey: "orderPosition")
context.save(nil)
}
}
}
首先,带有检索对象所需的获取请求的数组不是很有效。只需使用a NSFetchedResultsController
,索引路径将自动指向您的对象。此外,您可以免费获得出色的内存和性能优化。
正如评论中指出的那样,您需要保存任何新订单。例如,viewWillDisappear
在重新订购中或刚订购之后。根据您的设置,可能类似于以下内容:
for var i = 0; i < self.fetchedResultsController.fetchedObjects.count; i++ {
let indexPath = NSIndexPath(row:i section:0)
var object = self.fetchedResultsController.objectAtIndexPath(indexPath)
object.orderPosition = i+1
}
self.managedObjectContext.save(nil)
确保将排序描述符添加到获取的结果控制器中。如果您决定不使用提取的结果控制器(不建议使用),则必须在提取请求中包括排序,以在中填充数据数组viewDidLoad
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句