简体   繁体   中英

swift - CoreData inManagedObjectContext is nil

I am trying to save data to coredata, but I got "unexpectedly found nil while unwrapping an Optional value" error from insertIntoManagedObjectContext. I double check the naming of my entity (Article), attributes (articleID, isFavorite).

But I couldnt found the cause of the error.

            func saveArticleAsFav(articleID: Int){

            let isFav = true

            let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
            let managedContext = appDelegate.managedObjectContext!


            let entity = NSEntityDescription.entityForName("Article", inManagedObjectContext: managedContext)

            // Error here:
            let item = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext)

            item.setValue(articleID, forKey: "articleID")
            item.setValue(isFav, forKey:"isFavorite")

            var error: NSError?
            if !managedContext.save(&error){
                println("Could not save \(error), \(error?.userInfo)")
            }

            articleLocalData.append(item)
            println(self.articleLocalData)

        }

Edit: I tried to initialize coredata:

import Foundation
import CoreData

class saveArticleAsFav {

    var articleLocalData = [NSManagedObject]()

    var context:NSManagedObjectContext


    init(context:NSManagedObjectContext) {
        self.context = context
    }

    func saveArticleAsFav(articleID: Int){

        let isFav = true
        let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        let managedContext = appDelegate.managedObjectContext!

        let entity = NSEntityDescription.entityForName("Article", inManagedObjectContext: managedContext)
        let item = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext)

        item.setValue(articleID, forKey: "articleID")
        item.setValue(isFav, forKey:"isFavorite")

        var error: NSError?
        if !managedContext.save(&error){
            println("Could not save \(error), \(error?.userInfo)")
        }

        articleLocalData.append(item)
        println(self.articleLocalData)

    }
}

Then I call the func in my mail tableview: and got the following error: "Cannot invoke initializer for type 'saveArticleAsFav' with an argument list of type '(articleID: Int)'"

saveArticleAsFav(articleID: articleID!)

The only optional you are force unwrapping with ! in the offending line is entity . It follows that entity might be nil .

One reason could be that the entity name in your model is not "Article" .

I usually do not use the entity, but insert the object directly with Apple's convenience method using just the entity name.

let item = NSEntityDescription.insertNewObjectForEntityForName(
           "Article", inManagedObjectContext: managedContext) as Article

This method will fail if either the name is not correct or the context is not valid.

Note that the Swift compiler does not always give you the exact reason. It could be that the calling function passes an invalid articleID .

Besides, you have some serious flaws in the code you posted. Your init method implies that the managed object context is created somewhere else and that the class needs to be initialized using a valid context. That seems a pretty cumbersome way to provide a managed object context. You proceed by ignoring it and using another context from the app delegate.

Also, your class name looks really like a method. What kind of class is this supposed to be? By convention, classes should start with a capital letter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM