尝试实现NSFetchedResultsController后,由于未捕获的异常'NSInvalidArgumentException',我的Xcode应用程序崩溃了

时间:2019-06-19 06:59:39

标签: ios swift core-data crash nsfetchedresultscontroller

我最近问了一个有关如何为我的CoreData实体实现删除功能的问题。 (这里:How do I delete CoreData entries in a tableview that uses a persistentcontainer?),我被告知应该使用NSFetchResultsController,因此我开始着手研究。我以为我没错,我的代码现在在运行后立即崩溃。

我尝试使用教程来实现FetchedResultsController。我很确定自己已经正确执行了所有步骤,以将其实施到我的应用中,但仍然崩溃。我的尝试在下面提供。我的原始代码在上面的段落中。

ViewController.swift

import UIKit
import CoreData

class ViewController: UITableViewController {

    //var alarmItems: [NSManagedObject] = []
    let cellId = "cellId"

    private let persistentContainer = NSPersistentContainer(name: "AlarmItems")

    fileprivate lazy var fetchedResultsController: NSFetchedResultsController<AlarmItems> = {
        //create fetch request
        let fetchRequest: NSFetchRequest<AlarmItems> = AlarmItems.fetchRequest()

        //configure fetch request
        //fetchRequest.sortDescriptors = [NSSortDescriptor(key: )]

        let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.persistentContainer.viewContext, sectionNameKeyPath: nil, cacheName: nil)

        fetchedResultsController.delegate = self as? NSFetchedResultsControllerDelegate

        return fetchedResultsController
    }()


    override func viewDidLoad() {
        super.viewDidLoad()


    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        //guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
        //let managedContext = appDelegate.persistentContainer.viewContext
        //let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "AlarmItems")
        do {
            //alarmItems = try managedContext.fetch(fetchRequest)
            try fetchedResultsController.performFetch()
        } catch let err as NSError {
            print("Failed to fetch items", err)
        }
    }

    @objc func addAlarmItem(_ sender: AnyObject) {
        //print("this works")
        let alertController = UIAlertController(title: "Add New Item", message: "Please fill in the blanks", preferredStyle: .alert)
        let saveAction = UIAlertAction(title: "Save", style: .default) { [unowned self] action in

            //combined string of attributes
            let myStrings: [String] = alertController.textFields!.compactMap { $0.text }
            let myText = myStrings.joined(separator: ", ")

            self.save(myText)
            self.tableView.reloadData()
        }
        let cancelAction = UIAlertAction(title: "Cancel", style: .destructive, handler: nil)

        alertController.addTextField { (textField) in
            textField.placeholder = "Enter Name of Engineer"
        }
        alertController.addTextField { (textField) in
            textField.placeholder = "Enter Date of Alarm in DD/MM/YYYY"
        }
        alertController.addTextField { (textField) in
            textField.placeholder = "Enter Time of Alarm in 24h (eg: 2300)"
        }
        alertController.addTextField { (textField) in
            textField.placeholder = "Please indicate True/False (type True or False)"
        }
        alertController.addTextField { (textField) in
            textField.placeholder = "Insert comments (if any), or NIL"
        }


        alertController.addAction(saveAction)
        alertController.addAction(cancelAction)
        present(alertController, animated: true, completion: nil)
    }

    func save(_ itemName: String) {
        guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
        let managedContext = appDelegate.persistentContainer.viewContext
        let entity = NSEntityDescription.entity(forEntityName: "AlarmItems", in: managedContext)!
        let item = NSManagedObject(entity: entity, insertInto: managedContext)
        item.setValue(itemName, forKey: "alarmAttributes")


        do {
            try managedContext.save()
            //NSFetchedResultsController.append(item)
            tableView.reloadData()

        } catch let err as NSError {
            print("Failed to save an item", err)
        }
    }

    @objc func exportCSV(_ sender: AnyObject) {
        //will work on exporting csv in the future
        return
    }
    override func numberOfSections(in tableView: UITableView) -> Int {
        return fetchedResultsController.sections?.count ?? 0
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        //return alarmItems.count
        let sectionInfo = fetchedResultsController.sections![section]
        return sectionInfo.numberOfObjects
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
        let alarmItem = fetchedResultsController.object(at: indexPath)
        cell.textLabel?.text = alarmItem.value(forKeyPath: "alarmAttributes") as? String
        return cell
    }


}
  • 错误是:
      

    由于未捕获的异常“ NSInvalidArgumentException”而终止应用程序,原因:“ NSFetchedResultsController的实例需要非零的fetchRequest和managedObjectContext”

他们还说,即使我的代码中已经具有提取请求功能,也无法加载名为AlarmItems的模型。

1 个答案:

答案 0 :(得分:1)

首先删除let persistentContainer = NSPersistentContainer(name: "AlarmItems")并从AppDelegate中获取上下文

错误不完整

  

NSFetchedResultsController的实例需要一个非空的fetchRequest ,具有排序描述符和managedObjectContext

fileprivate lazy var fetchedResultsController: NSFetchedResultsController<AlarmItems> = {
    //create fetch request
    let fetchRequest: NSFetchRequest<AlarmItems> = AlarmItems.fetchRequest()

    //configure fetch request
    fetchRequest.sortDescriptors = [NSSortDescriptor(key: "alarmAttributes", ascending: true)]
    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

    let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)

    fetchedResultsController.delegate = self

    return fetchedResultsController
}()

正如已经提到的,请以单数形式NSManagedObject命名AlarmItem子类