swift编程核心数据获取ResultsController.sections无错误

swift编程核心数据获取ResultsController.sections无错误,swift,core-data,Swift,Core Data,数据库中填充了一条节标题记录,这是一种多(用户指令)对一(节标题)关系,“fetchedResultsController.sections”返回nil 致命错误:FRC未正确配置:文件/Users/tae/Documents/Assignments/BrickMatcherV5/BrickMatcherV5/Controllers/InformationViewController.swift,第101行 2019-12-18 18:18:18.406622+0000 BrickMatcher

数据库中填充了一条节标题记录,这是一种多(用户指令)对一(节标题)关系,“fetchedResultsController.sections”返回nil

致命错误:FRC未正确配置:文件/Users/tae/Documents/Assignments/BrickMatcherV5/BrickMatcherV5/Controllers/InformationViewController.swift,第101行 2019-12-18 18:18:18.406622+0000 BrickMatcherV5[3924:121317]致命错误:FRC未正确配置:文件/Users/tae/Documents/Assignments/BrickMatcherV5/BrickMatcherV5/Controllers/InformationViewController.swift,第101行

import UIKit
import CoreData

class InformationViewController: UITableViewController {

    let cellId = "sdlfjowieurewfn34898442249sd;ds;lfkds;f47824dslaksjfs;ad"

    var model: UserInstructionsModel!
    let defaults = UserDefaults.standard
    var networkManager = NetworkManager.shared
    var instructionURLComponents = URLComponents()

    // Create a reference to the CoreData Stack
    private let cdStack = CoreDataStack.shared

    // The all mighty FetchedResultsController
    fileprivate lazy var fetchedResultsController: NSFetchedResultsController <UserInstruction> = {

        let fetchRequest:NSFetchRequest =  UserInstruction.fetchRequest()
        fetchRequest.sortDescriptors = [NSSortDescriptor(key: "sectionHeading.name", ascending: true),
        NSSortDescriptor(key: "rowOrder", ascending: true)]

        //managedObjectContext is your instance of NSManagedObjectContext
        let fetchedResultsContoller = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: CoreDataStack.shared.mainContext, sectionNameKeyPath: "sectionHeading.name", cacheName: nil)
        fetchedResultsContoller.delegate = self
        return fetchedResultsContoller
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        navigationItem.title = "How To Use"
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
        tableView.register(SubtitleTableViewCell.self, forCellReuseIdentifier: cellId)
        tableView.tableFooterView = UIView(frame: CGRect.zero)
        model = UserInstructionsModel(coreDataStack: CoreDataStack.shared)
        fetchHelpInstructions()

        do {
            try fetchedResultsController.performFetch()
            print("try done")
        } catch let fetchError {
            print("Fetch Error: \(fetchError.localizedDescription)")
        }

        // Set the Show Help Screen Switch
        self.defaults.set(true, forKey: "seenHelpInformation")
    }

    private func fetchHelpInstructions() {

        let seenHelpInformation = self.defaults.bool(forKey: "seenHelpInformation")

        if seenHelpInformation == false {

            instructionURLComponents.scheme = ProcessingServer.scheme
            instructionURLComponents.host = ProcessingServer.host
            instructionURLComponents.port = ProcessingServer.port
            instructionURLComponents.path = EndPoints.instructions
            networkManager.fetchInstructions(url: instructionURLComponents.url!, completion: { Instruction in

                guard let serverInstructions = Instruction else { return }

                do {
                    try self.model.saveInstructions(instructions: serverInstructions)
                } catch {

                    let alertController = UIAlertController(title: "Error Saving Instructions", message: error as? String, preferredStyle: .alert)
                    let OKAction = UIAlertAction(title: "OK", style: .default) { action in
                        print("Pressed OK")
                    }
                    alertController.addAction(OKAction)
                    self.present(alertController, animated: true, completion: nil)
                }
            })
        }
    }
}


extension InformationViewController {

    // MARK: - Table view data source
    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

        guard let sections = fetchedResultsController.sections else { fatalError("No Sections") }

        let sectionInformation = sections[section]
        return sectionInformation.name
    }

    override func numberOfSections(in tableView: UITableView) -> Int {

        guard let sections = fetchedResultsController.sections else { fatalError("FRC not configuired correctly") }
        return sections.count
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        guard let sections = fetchedResultsController.sections else { fatalError("FRC not configuired correctly") }

        let sectionInformation = sections[section]
        return sectionInformation.numberOfObjects
    }


    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)

        let instruction = fetchedResultsController.object(at: indexPath)

        cell.textLabel?.text = instruction.headlineDisplayText
        cell.detailTextLabel?.text = instruction.descriptionDisplayText

        return cell
    }

    class SubtitleTableViewCell: UITableViewCell {

        override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
            super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
        }

        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    }
}

extension InformationViewController : NSFetchedResultsControllerDelegate {

func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, sectionIndexTitleForSectionName sectionName: String) -> String? {
    return String(sectionName.hashValue)
}
}
导入UIKit
导入CoreData
类信息ViewController:UITableViewController{
let cellId=“sdlfjowieurewfn34898442249sd;ds;lfkds;f47824dslaksjfs;ad”
var模型:UserInstructionsModel!
让defaults=UserDefaults.standard
var networkManager=networkManager.shared
var instructionURLComponents=URLComponents()
//创建对CoreData堆栈的引用
私有let cdStack=CoreDataStack.shared
//全能的FetchedResultsController
fileprivate惰性变量fetchedResultsController:NSFetchedResultsController={
let fetchRequest:NSFetchRequest=UserInstruction.fetchRequest()
fetchRequest.sortDescriptors=[NSSortDescriptor(键:“sectionHeading.name”,升序:true),
NSSortDescriptor(键:“行顺序”,升序:true)]
//managedObjectContext是NSManagedObjectContext的实例
让fetchedResultsContoller=NSFetchedResultsController(fetchRequest:fetchRequest,managedObjectContext:CoreDataStack.shared.mainContext,sectionNameKeyPath:“sectionHeading.name”,cacheName:nil)
fetchedResultsContoller.delegate=self
返回获取的ResultsContoller
}()
重写func viewDidLoad(){
super.viewDidLoad()
view.backgroundColor=.white
navigationItem.title=“如何使用”
tableView.register(UITableViewCell.self,forCellReuseIdentifier:cellId)
tableView.register(SubtitleTableViewCell.self,forCellReuseIdentifier:cellId)
tableView.tableFooterView=UIView(帧:CGRect.zero)
model=UserInstructionsModel(coreDataStack:coreDataStack.shared)
fetchHelpInstructions()
做{
请尝试fetchedResultsController.performFetch()
打印(“尝试完成”)
}catch-let-fetchError{
打印(“获取错误:\(获取错误.localizedDescription)”)
}
//设置显示帮助屏幕开关
self.defaults.set(true,forKey:“seenHelpInformation”)
}
私有函数fetchHelpInstructions(){
让seenHelpInformation=self.defaults.bool(forKey:“seenHelpInformation”)
如果seenHelpInformation==false{
instructionURLComponents.scheme=ProcessingServer.scheme
指令UrlComponents.host=ProcessingServer.host
instructionURLComponents.port=ProcessingServer.port
instructionURLComponents.path=端点.instructions
networkManager.fetchInstructions(url:instructionURLComponents.url!,完成:{中的指令
guard let serverInstructions=指令else{return}
做{
尝试self.model.saveInstructions(说明:服务器说明)
}抓住{
让alertController=UIAlertController(标题:“错误保存说明”,消息:错误为?字符串,首选样式:。警报)
让OKAction=UIAlertAction(标题:“OK”,样式:。默认值){action in
打印(“按下OK”)
}
alertController.addAction(OKAction)
self.present(alertController,动画:true,完成:nil)
}
})
}
}
}
扩展信息视图控制器{
//标记:-表视图数据源
重写func tableView(tableView:UITableView,titleForHeaderInSection:Int)->String{
guard let sections=fetchedResultsController.sections else{fatalError(“无节”)}
让sectionInformation=节[节]
返回sectionInformation.name
}
重写func numberOfSections(在tableView:UITableView中)->Int{
guard let sections=fetchedResultsController.sections else{fatalError(“FRC未正确配置”)}
返回节数
}
重写func tableView(tableView:UITableView,numberofrowsinssection:Int)->Int{
guard let sections=fetchedResultsController.sections else{fatalError(“FRC未正确配置”)}
让sectionInformation=节[节]
返回sectionInformation.numberOfObjects
}
重写func tableView(tableView:UITableView,cellForRowAt indexath:indexPath)->UITableViewCell{
let cell=tableView.dequeueReusableCell(标识符:cellId,for:indexath)
let指令=fetchedResultsController.object(位于:indexPath)
cell.textLabel?.text=指令.headlineDisplayText
cell.detailTextLabel?.text=指令.descriptionDisplayText
返回单元
}
类TableViewCell:UITableViewCell{
重写init(样式:UITableViewCell.CellStyle,reuseIdentifier:String?){
super.init(样式:。副标题,reuseIdentifier:reuseIdentifier)
}
必需的初始化?(编码器aDecoder:NSCoder){
fatalError(“初始化(编码者:)尚未实现”)
}
}
}
扩展信息ViewController:NSFetchedResultsControllerDelegate{
func控制器(u控制器:NSFetchedResultsController,sectionIndexTitleForSectionName sectionName:String)->String{
返回字符串(sectionName.hashValue)
}
}
模型细节


要正确显示节,必须在第一个位置指定一个排序描述符,该描述符对应
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "sectionHeading.name", ascending: true),
                                NSSortDescriptor(key: "rowOrder", ascending: true)]
override func numberOfSections(in tableView: UITableView) -> Int {
    return fetchedResultsController.sections?.count ?? 0
}