【发布时间】:2015-10-07 09:21:20
【问题描述】:
我正在尝试使用核心数据和 nsfetchresultscontroller 重新排序表格视图中的单元格。我发现了一些使用 Objective C 的方法(我对此一无所知)并尝试快速实现它们,这就是我想出的:
var books: Array<AnyObject> = []
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
books = fetchedResultsController.fetchedObjects!
let book = fetchedResultsController.objectAtIndexPath(fromIndexPath)
self.fetchedResultsController.delegate = nil
books.removeAtIndex(fromIndexPath.row)
books.insert(book, atIndex: toIndexPath.row)
var i = 0
for book in books {
book.setValue(i++, forKey: "position")
}
try! context.save()
self.fetchedResultsController.delegate = self
}
委托和上下文引用在另一个文件的扩展中。 使用此代码有时可以工作,有时不能。我更改了顺序,再次运行应用程序,它的顺序完全不同,我无法弄清楚。尤其是当我一次移动不止一排时。如果我将每个对象的“位置”属性打印到控制台,我可以看到它们确实没有正确更新。但为什么不呢?
我做错了什么?什么是更好的选择?
提前致谢,
丹尼尔
编辑:
好的,下面是工作代码:
func initializeFetchedResultsController() {
let request = NSFetchRequest(entityName: "Book")
let sortDescriptor = NSSortDescriptor(key: "position", ascending: true)
request.sortDescriptors = [sortDescriptor]
self.fetchedResultsController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
self.fetchedResultsController.delegate = self
do {
try self.fetchedResultsController.performFetch()
} catch {
fatalError("Failed to initialize FetchedResultsController: \(error)")
}
}
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
initializeFetchedResultsController()
var objects = self.fetchedResultsController.fetchedObjects! as! [ObjectClass]
self.fetchedResultsController.delegate = nil
let object = objects[fromIndexPath.row]
objects.removeAtIndex(fromIndexPath.row)
objects.insert(object, atIndex: toIndexPath.row)
var i = 0
for object in objects {
object.position = i++
}
try! context.save()
self.fetchedResultsController.delegate = self
}
诀窍是 initializeFetchedResultsController 函数,除了在 viewDidLoad 中,我有它,必须在 moveRowAtIndexPath 位内重复。此外,初始化函数和数组声明都必须在将 FRC 委托设置为 nil 之前(很明显,但很容易错过)。
【问题讨论】:
标签: ios swift uitableview core-data nsfetchedresultscontroller