【问题标题】:Swift 3 - Program crashes when trying to perform fetch requestSwift 3 - 尝试执行获取请求时程序崩溃
【发布时间】:2017-07-09 21:39:17
【问题描述】:

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

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 上具有完全相同的代码,并且没有崩溃。有任何想法吗?任何帮助将不胜感激。

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

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)

【问题讨论】:

  • 不知道是不是问题,但是你的 fetch 控制器没有委托
  • 我假设 'context' 为 nil。
  • “以 NSException 类型的未捕获异常终止”它不是特定错误。正确包含完整的错误日志
  • 查看问题 here 的 cmets 并查看其答案
  • @Chandan 上下文在应用委托中定义,它本质上是一个快捷变量,定义为 appdelegate.persistentcontainer.viewContext

标签: ios swift xcode swift3 ios10


【解决方案1】:

错误信息很清楚:

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)

【讨论】:

  • 我不知道我是怎么错过的,但你回答了我的问题。谢谢!
猜你喜欢
  • 1970-01-01
  • 2016-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-22
  • 1970-01-01
相关资源
最近更新 更多