iOS:Swift:核心数据:错误:+ entityForName:nil不是合法的NSManagedObjectContext参数,用于搜索实体名称

时间:2014-08-23 11:54:39

标签: ios swift core-data nsmanagedobjectcontext

我使用Core Data作为Swift语言的表格视图。它可以成功启动,但在AddView中单击完成按钮后,出现错误:

由于未捕获的异常终止应用程序' NSInvalidArgumentException',原因:' + entityForName:nil不是合法的NSManagedObjectContext参数,用于搜索实体名称' OneItemCD''

我不知道为什么。有人能帮帮我搞清楚吗?非常感谢!

这是代码。有一个添加栏按钮项。单击此按钮将转移到AddViewController。在文本视图中键入内容并单击“完成”按钮后,转移回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.
}

}

我将整个代码放在github中:

https://github.com/snowffer/testTableViewForCoreData

1 个答案:

答案 0 :(得分:1)

当您设置var fetchedResultsController时,您的managedObjectContext仍为nil。因此,当您声明:

时,您的应用会崩溃
let entity = NSEntityDescription.entityForName("OneItemCD", inManagedObjectContext: self.managedObjectContext)

确保在拨打上一行代码之前正确设置managedObjectContext

还有一件事

要在您的Core Data模型中使用OneItemCD的Swift子类,请在模型实体检查器的Class字段中使用模块名称作为类名的前缀,如下所示:" testTableViewCoreData。 OneItemCD" (查看有关核心数据和名称空间here)的更多信息。