Swift 3 - 尝试执行获取请求时程序崩溃

Spe*_*nak 1 xcode ios swift swift3 ios10

目前,我正在尝试在我的一个视图控制器上获取歌曲类型的实体。这是相关的代码,我有:

import CoreData

class TimerScreenVC: UIViewController, NSFetchedResultsControllerDelegate {

var songController: NSFetchedResultsController<Song>!


override function viewDidLoad() {
   super.viewdidLoad()
   attemptSongFetch()
}


func attemptSongFetch() {
    let fetchRequest: NSFetchRequest<Song> = Song.fetchRequest()
    let controller = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
    let sortByTitle = NSSortDescriptor(key: "title", ascending: true)
    fetchRequest.sortDescriptors = [sortByTitle]
    songController = controller
    do {
        try songController.performFetch()
    } catch {
        let error = error as NSError
        print("\(error)")
    }


}


    func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
    print("called will change")
}
    func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
    print("called did change")
}
    func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
    switch (type) {
    case .insert:
        print("has been called")
    default:
        print("has been called")
    }

}
}
Run Code Online (Sandbox Code Playgroud)

但是,当我加载这个视图控制器时,我遇到了“以 NSException 类型的未捕获异常终止”的错误。如果我在viewDidLoad() 中注释掉attemptSongFetch(),我可以使错误消失并且程序运行良好,但我需要调用该函数。

我也有完全相同的功能,attemptSongFetch(),在另一个 ViewController 上有完全相同的代码,并且没有崩溃。有任何想法吗?任何帮助将不胜感激。

更新所以这是错误,它告诉我我需要设置排序描述,这很奇怪,因为它已经定义了?:

017-02-20 15:48:21.006 Alarm Clock[10433:158613] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'An instance of NSFetchedResultsController requires a fetch request with sort descriptors' libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)

vad*_*ian 5

错误信息非常清楚:

NSFetchedResultsController 的实例需要带有排序描述符的 fetch 请求

目前您正在创建NSFetchedResultsController没有排序描述符(还)。只需重新排序行:

let fetchRequest: NSFetchRequest<Song> = Song.fetchRequest()
let sortByTitle = NSSortDescriptor(key: "title", ascending: true)
fetchRequest.sortDescriptors = [sortByTitle]
let controller = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
Run Code Online (Sandbox Code Playgroud)