2017-02-20 13 views
0

現在、私はView Controllerの1つでタイプソングのエンティティを取得しようとしています。私は、このビューコントローラをロードする際Swift 3 - フェッチ要求を実行しようとするとプログラムがクラッシュする

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()でtrySongFetch()をコメントアウトするとエラーが消えてプログラムが正常に動作しますが、その関数を呼び出す必要があります。

また、別のViewController &に全く同じコードのtrySongFetch()がありますが、私は全く同じ機能を持っていますが、クラッシュしていません。何か案は?どんな助けでも大歓迎です。

更新はので、ここでエラーがだ、すでに定義されていますので、私は奇妙なソートの説明を、設定する必要があることを私に言っています?:

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)

+0

私がそれを知ることはできませんが、フェッチコントローラにはデリゲートがありません – CZ54

+0

「コンテキスト」がnilであると仮定しています。 – Chandan

+1

"NSException型のキャッチされていない例外で終了"、それは特定のエラーではありません。 **フルエラーログ**を正しく含めてください。 –

答えて

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) 
+0

私はそれを逃したのか分かりませんが、私の質問に答えました。ありがとう! –

関連する問題