gpt4 book ai didi

xcode - Swift 中核心数据的自动重新排序

转载 作者:行者123 更新时间:2023-11-28 13:17:53 26 4
gpt4 key购买 nike

在“编辑模式”中移动单元格时,我试图重新排序我的核心数据列表。在这个领域似乎有针对 Obj-c 的有益讨论(请参阅下面的链接),但我在 Swift 中找不到任何内容。

有没有人看过 Swift 的相关文档?或者有人愿意将 obj-c 代码翻译成 Swift 吗?谢谢!

Obj-c 链接:

How can I maintain display order in UITableView using Core Data?

How to implement re-ordering of CoreData records?

最佳答案

这是我做的一个很好的方法。它还会检查目标是否不包含任何数据,您也可以跨部分移动。isMoving 将禁止委托(delegate)启动。您的实体还需要一个 sortorder 属性。

private func indexIsOutOfRange(indexPath:NSIndexPath) -> Bool {
if indexPath.section > self.fetchedResultsController.sections!.count - 1 {
return true
}
if indexPath.row > self.fetchedResultsController.sections![indexPath.section].objects!.count - 1 {
return true
}
return false
}

override func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath)
{
if indexIsOutOfRange(destinationIndexPath) {
return
}

isMovingItem = true


if sourceIndexPath.section == destinationIndexPath.section {
if var todos = self.fetchedResultsController.sections![sourceIndexPath.section].objects {
let todo = todos[sourceIndexPath.row] as! FoodEntry
todos.removeAtIndex(sourceIndexPath.row)
todos.insert(todo, atIndex: destinationIndexPath.row)

var idx = 1
for todo in todos as! [FoodEntry] {
todo.sortOrder = NSNumber(integer: idx++)
}
try!managedObjectContext.save()
}
} else {

if var allObjectInSourceSection = fetchedResultsController.sections![sourceIndexPath.section].objects {
let object = allObjectInSourceSection[sourceIndexPath.row] as! FoodEntry
allObjectInSourceSection.removeAtIndex(sourceIndexPath.row)

for (index,object) in (allObjectInSourceSection as! [FoodEntry]).enumerate() {
object.sortOrder = NSNumber(integer: index)
}


if var allObjectInDestinationSection = fetchedResultsController.sections![destinationIndexPath.section].objects {

allObjectInDestinationSection.insert(object, atIndex: destinationIndexPath.row)

for (index,object) in (allObjectInDestinationSection as! [FoodEntry]).enumerate() {
object.sortOrder = NSNumber(integer: index)
object.section = NSNumber(integer: destinationIndexPath.section)
}
}
}

}


dispatch_async(dispatch_get_main_queue(), { () -> Void in
tableView.reloadRowsAtIndexPaths(tableView.indexPathsForVisibleRows!, withRowAnimation: .Fade)
})

isMovingItem = false

try!managedObjectContext.save()

fetch()

}

关于xcode - Swift 中核心数据的自动重新排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28243643/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com