如何使用存储的整数属性从Core Data中对数组进行排序?

时间:2015-06-16 02:30:23

标签: ios arrays swift uitableview core-data

我正在尝试使用Core Data来使用moveRowAtIndexPath方法。我的程序是用户驱动的,意味着用户反复更新数据,基本上是一个显示实体名称的表视图。每个实体都有两个属性:一个名称和一个表示它在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)
        }
    }
}

2 个答案:

答案 0 :(得分:1)

您可以创建NSSortDescriptor来获取数据:

let sortDescriptor = NSSortDescriptor(key: "orderPosition", ascending: true)
let sortDescriptors = [sortDescriptor]
fetchReq.sortDescriptors = sortDescriptors

答案 1 :(得分:0)

首先,具有检索对象所需的获取请求的数组效率不高。只需使用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中填充数据数组。