iOS: Swift: Core Data: Error: +entityForName: nil is not a legal NSManagedObjectContext parameter searching for entity name

安稳与你 提交于 2020-01-04 02:41:07

问题


I used Core Data for a table view with Swift Language. It can launch successfully, but after clicking Done button in AddView, there is an error:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+entityForName: nil is not a legal NSManagedObjectContext parameter searching for entity name 'OneItemCD''

I don't know why. Could anybody help me figure it out? Thanks very much!

Here is the code. There is an add bar button item. Clicking this button transfer to AddViewController. After typing something in the text view and clicking Done button, transfer back to TableViewController.

TableViewController:

import UIKit
import CoreData

class TableViewController: UITableViewController, NSFetchedResultsControllerDelegate {

var managedObjectContext: NSManagedObjectContext? = nil

override func viewDidLoad() {
    super.viewDidLoad()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView!) -> Int {

    return 1
}

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

    return 0
}

@IBAction func unwindToList(segue: UIStoryboardSegue) {

    var source: AddViewController = segue.sourceViewController as AddViewController
    source.managedObjectContext = self.managedObjectContext
    var noteContent: String? = source.contentBody.text

    if noteContent != nil {

        let context = self.fetchedResultsController.managedObjectContext
        let entity = self.fetchedResultsController.fetchRequest.entity
        let newManagedObject = NSEntityDescription.insertNewObjectForEntityForName(entity.name, inManagedObjectContext: context) as NSManagedObject

        newManagedObject.setValue(noteContent, forKey: "content")

        var error: NSError? = nil
        if !context.save(&error) {

            abort()
        }
        self.tableView.reloadData()
    }


}


// MARK: - Fetched results controller

var fetchedResultsController: NSFetchedResultsController {
    if _fetchedResultsController != nil {
        return _fetchedResultsController!
        }

        let fetchRequest = NSFetchRequest()
        // Edit the entity name as appropriate.
        let entity = NSEntityDescription.entityForName("OneItemCD", inManagedObjectContext: self.managedObjectContext)
        fetchRequest.entity = entity

        // Set the batch size to a suitable number.
        fetchRequest.fetchBatchSize = 20

        // Edit the sort key as appropriate.
        let sortDescriptor = NSSortDescriptor(key: "content", ascending: false)
        let sortDescriptors = [sortDescriptor]

        fetchRequest.sortDescriptors = [sortDescriptor]

        // Edit the section name key path and cache name if appropriate.
        // nil for section name key path means "no sections".
        let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext, sectionNameKeyPath: nil, cacheName: "Master")
        aFetchedResultsController.delegate = self
        _fetchedResultsController = aFetchedResultsController

        var error: NSError? = nil
        if !_fetchedResultsController!.performFetch(&error) {

            abort()
        }

        return _fetchedResultsController!
}    
var _fetchedResultsController: NSFetchedResultsController? = nil

}

AddViewController:

import UIKit
import CoreData

class AddViewController: UIViewController {


@IBOutlet weak var contentBody: UITextView!

var managedObjectContext: NSManagedObjectContext? = nil

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

I put my entire code in github:

https://github.com/snowffer/testTableViewForCoreData


回答1:


When you set var fetchedResultsController, your managedObjectContext is still nil. Therefore, your app crashes when you declare:

let entity = NSEntityDescription.entityForName("OneItemCD", inManagedObjectContext: self.managedObjectContext)

Make sure to set managedObjectContext correctly before you call the previous line of code.

One more thing:

To use a Swift subclass of OneItemCD with your Core Data model, prefix the class name in the Class field of the model entity inspector with the name of your module, just like this: "testTableViewCoreData.OneItemCD" (See more about Core Data and namespaces here).



来源:https://stackoverflow.com/questions/25461662/ios-swift-core-data-error-entityforname-nil-is-not-a-legal-nsmanagedobject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!