NSFetchedResultsController 在创建时崩溃,objc_exception_throw

NSFetchedResultsController crashing when creating it, objc_exception_throw

我在创建 NSFetchedResultsController 时收到 objc_exception_throw。我对 iOS 编程比较陌生,所以我仍然掌握调试 iOS 崩溃的窍门。

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
lazy var parentContext: NSManagedObjectContext? = {
    if let managedObjectContext = self.appDelegate.managedObjectContext {
        return managedObjectContext
    }
    else {
        return nil
    }
    }()

lazy var fetchedResultsController: NSFetchedResultsController = {
    let request = NSFetchRequest()
    let entity = NSEntityDescription.entityForName("GameDate", inManagedObjectContext: self.parentContext!)
    request.entity = entity
    let frc = NSFetchedResultsController(fetchRequest: request, managedObjectContext: self.parentContext!, sectionNameKeyPath: nil, cacheName: nil)
    frc.delegate = self
    return frc
}()

override func viewDidLoad() {
    super.viewDidLoad()
    performFetchFromDb()
    setupTableView()
}

我在这条线上遇到了崩溃:

let frc = NSFetchedResultsController(fetchRequest: request, managedObjectContext: self.parentContext!, sectionNameKeyPath: nil, cacheName: nil)

这次崩溃与我的上下文有关吗?

我的提取请求中缺少 NSSortDescriptor。这修复了它:

lazy var fetchedResultsController: NSFetchedResultsController = {
    let request = NSFetchRequest()

    let entity = NSEntityDescription.entityForName("GameDate", inManagedObjectContext: self.parentContext!)
    request.entity = entity

    let gameTimeSort = NSSortDescriptor(key: "gameTime", ascending: false)
    request.sortDescriptors = [gameTimeSort]

    let frc = NSFetchedResultsController(fetchRequest: request, managedObjectContext: self.parentContext!, sectionNameKeyPath: nil, cacheName: nil)
    frc.delegate = self
    return frc
}()