从我的CoreData获取数据并使用Swift

时间:2015-07-12 03:44:17

标签: ios swift uitableview core-data fatal-error

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

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)
  

错误:致命错误:在打开时意外发现nil   可选值

1 个答案:

答案 0 :(得分:0)

你有一个财产:

public var context: NSManagedObjectContext!

您永远不会将其设置为NSManagedObjectContext,因此它为零。这是你在致命和意外发现的零。