'+entityForName: nil is not a legal NSManagedObjectContext parameter - Core Data

后端 未结 8 700
梦如初夏
梦如初夏 2020-11-28 22:26

I have added all of the relevant code to the App Delegate, and I am able to add to the data model and fetch from the data model in applicationDidFinishLaunchingWithOptions.<

相关标签:
8条回答
  • 2020-11-28 22:43

    You can pass the context by including the following code before you begin to fetch the data form the database:

    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
    context = [appDelegate managedObjectContext];
    
    0 讨论(0)
  • 2020-11-28 22:48

    I had forgotten to pass the context to the view controller. Rookie error.

    0 讨论(0)
  • 2020-11-28 22:53

    If you are using segues you will get the same problems if you don't pass the context down the line. Use this code in the prepareForSegue method of class initiating the segue:

    [[segue destinationViewController] setManagedObjectContext:self.managedObjectContext];
    

    That assumes you hold your context in a property called "managedObjectContext" of course.

    0 讨论(0)
  • 2020-11-28 22:58

    I got this problem and a colleague helped me out. If you got this error message: "entityForName: nil is not a legal NSManagedObjectContext parameter searching for entity name". And you made changes in you coredata model. I think the problem might not be the code.

    The solution can be simple. Try one of those options:

    • Just delete the app from the device you are testing, it should have the old version of your model.
    • Create another database version using Xcode, >Editor>Add Model Version.

    Hope it helps.

    0 讨论(0)
  • 2020-11-28 22:59

    I'm a fan of lazy initialization. This way if you need to inject a new context for testing you can, or it'll get it's context from the app delegate if you set up your MOC there.

    class.h
    @property (strong, nonatomic,getter=getManagedObjectContext) NSManagedObjectContext *managedObjectContext;
    
    class.m
        -(NSManagedObjectContext *)getManagedObjectContext {
            if (_managedObjectContext) {
                return _managedObjectContext;
            }
            _managedObjectContext = [[(AppDelegate *)[[UIApplication sharedApplication]delegate]sharedDataModel]managedObjectContext];
            return _managedObjectContext;
        }
    
    0 讨论(0)
  • 2020-11-28 23:02

    you should add this to your viewController:

     id delegate = [[UIApplication sharedApplication] delegate];
        self.managedObjectContext = [delegate managedObjectContext];
    
    0 讨论(0)
提交回复
热议问题