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

时间:2017-02-20 14:42:43

标签: ios swift xcode 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")
    }

}
}

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

我也有完全相同的函数,attemptSongFetch(),在另一个ViewController&amp;上有完全相同的代码。那一个没有崩溃。有任何想法吗?任何帮助将不胜感激。

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

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)

1 个答案:

答案 0 :(得分:3)

错误信息非常清楚:

  

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

在您创建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)