需要提示,在花费几个小时与NSFetchedResultsController挣扎后放弃。
错误消息是:
CoreData:错误:NSFetchedResultsController:索引处没有对象 2147483647在索引0的部分
...但我甚至不知道是谁解雇了这个错误。我的代码的最后一部分是saveContext(),下一个断点在didChange内。
class ViewController : UITableViewController, NSFetchedResultsControllerDelegate
private lazy var channelController: NSFetchedResultsController<ZChannel> = {
let appDelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
let request: NSFetchRequest<ZChannel> = ZChannel.fetchRequest()
request.sortDescriptors = [NSSortDescriptor(key: "kit", ascending: true), NSSortDescriptor(key: "name", ascending: true)]
let retval: NSFetchedResultsController<ZChannel> = NSFetchedResultsController(fetchRequest: request,
managedObjectContext: appDelegate.persistentContainer.viewContext,
sectionNameKeyPath: "kit",
cacheName: nil)
retval.delegate = self
return retval
}()
public init() {
super.init(style: .grouped)
self.tableView.register(ChannelTableCell.self, forCellReuseIdentifier: "ChannelTableCell")
let appDelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.persistentContainer.viewContext.perform {
do {
try self.channelController.performFetch()
} catch {
let e = error as NSError
fatalError("[CoreData] Unresolved fetch error \(e), \(e.userInfo)")
}
}
}
public func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch(type) {
case .insert:
self.tableView?.insertRows(at: [newIndexPath!], with: .bottom)
break;
case .update:
self.tableView?.reloadRows(at: [indexPath!], with: .bottom)
break
default:
break
}
}
public func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) {
switch (type) {
case .insert:
self.tableView?.insertSections(IndexSet(integer: sectionIndex), with: UITableViewRowAnimation.bottom)
break
case .delete:
self.tableView?.deleteSections(IndexSet(integer: sectionIndex), with: UITableViewRowAnimation.bottom)
break
default:
break
}
}
从另一个线程我插入新对象:
self.persistentContainer.viewContext.performAndWait
{
// ...
let channel: ZChannel = NSEntityDescription.insertNewObject(forEntityName: "ZChannel", into: self.persistentContainer.viewContext) as! ZChannel
// ...
self.saveContext()
}
答案 0 :(得分:1)
一些问题:
indexOfObject
之类的内容并假设它在数组中,然后使用可能导致崩溃的索引。 self.channelController.performFetch()
内调用您已经在主线程上的persistentContainer.viewContext.perform