从我的 CoreData 获取数据并使用 Swift 在 Table 视图中显示时出现致命错误

Fatal error when fetch data from my CoreData and presented it in a Table View using Swift

我一直在尝试寻找一种方法来从我的 CoreData 获取数据并将其显示在我的 TableView 的单元格中。 Cell 有一个标题和一个副标题,其中标题将包含内容的主题,副标题将包含日期。我尝试了几种不同的方法,我采用的路径没有给我任何语法错误,但我收到调试错误。

public class SecondViewController: UIViewController, UITableViewDelegate, UISearchBarDelegate, UISearchDisplayDelegate, UITableViewDataSource, NSFetchedResultsControllerDelegate {

    public var context: NSManagedObjectContext!

    @IBOutlet weak var tableView: UITableView!

    lazy var fetchedResultsController: NSFetchedResultsController = {
        let dataFetchedRequest = NSFetchRequest(entityName: "Data")
        let primarySortDescriptor = NSSortDescriptor(key: "Data.subject", ascending: true)
        dataFetchedRequest.sortDescriptors = [primarySortDescriptor]

        let frc = NSFetchedResultsController(
            fetchRequest: dataFetchedRequest,
            managedObjectContext: self.context,
            sectionNameKeyPath: "Data.subject",
            cacheName: nil)

        frc.delegate = self

        return frc

        }()

    override public func viewDidLoad() {
        var error: NSError? = nil
        if (fetchedResultsController.performFetch(&error) == false) {
            print("An error occurred: \(error?.localizedDescription)")
        }
    }

    public func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        if let sections = fetchedResultsController.sections {
            return sections.count
        }

        return 0
    }
    public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if let sections = fetchedResultsController.sections {
            let currentSection = sections[section] as! NSFetchedResultsSectionInfo
            return currentSection.numberOfObjects
        }

        return 0
    }

    public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
        let data = fetchedResultsController.objectAtIndexPath(indexPath) as! Data

        cell.textLabel?.text = data.subject
        cell.detailTextLabel?.text = data.date

        return cell
    }
}

let frc = NSFetchedResultsController(
        fetchRequest: dataFetchedRequest,
        **managedObjectContext: self.context,** <-- This line gives me error
        sectionNameKeyPath: "Data.subject",
        cacheName: nil)

error: fatal error: unexpectedly found nil while unwrapping an Optional value

你有一个属性:

public var context: NSManagedObjectContext!

您永远不会将其设置为 NSManagedObjectContext,因此它为零。那就是你意外发现的 nil。