73

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.

My problem comes when I am trying to write to the data model in my View Controller. I have added this code to the header file:

NSFetchedResultsController *fetchedResultsController;
NSManagedObjectContext *managedObjectContext;

@property (nonatomic, retain) NSFetchedResultsController *fetchedResultsController;
@property (nonatomic, retain) NSManagedObjectContext *managedObjectContext;

And this code to my implementation file:

NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *model = [NSEntityDescription
                          insertNewObjectForEntityForName:@"Events" 
                          inManagedObjectContext:context];
[model setValue:@"Sample Event" forKey:@"eventName"];

NSError *error;
if (![context save:&error]) {
    NSLog(@"Couldn't save: %@", [error localizedDescription]);
}

However, I get the following error:

'NSInvalidArgumentException', reason: '+entityForName: nil is not a legal NSManagedObjectContext parameter searching for entity name 'Events''

Does anyone know what's going on? Any help would be appreciated.

Alex Godbehere
  • 2,862
  • 6
  • 28
  • 52
  • 12
    I think the context is nil. Make sure [self managedObjectContext] is not returning nil – mask8 Jul 21 '12 at 23:19
  • 1
    Noting for posterity's sake, you can get this error if you pass the ivar for the ManagedObjectContext instead of using the getter method – Matthemattics Apr 07 '13 at 03:32

8 Answers8

46

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

Alex Godbehere
  • 2,862
  • 6
  • 28
  • 52
  • and this is the way to pass context to the view controller: AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication]delegate]; context = [appDelegate managedObjectContext]; – Syed Asad Ali Jan 09 '15 at 13:19
45

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];
Himanshu Jansari
  • 28,446
  • 26
  • 101
  • 128
Vishwani
  • 615
  • 6
  • 8
37

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.

Tim
  • 1,062
  • 12
  • 24
  • 1
    I set it to _managedObjectContext and it crashes. self.mangeObjectContext solve it. Thanks! – LE SANG Jun 22 '15 at 08:14
  • Glad it works! I believe that, post Xcode 4.4, if you just use "@synthesize myProperty;" the compiler creates an instance variable called "myProperty" rather than "_myProperty". If you don't use "@synthesize" at all you get "_myProperty". So "_managedObjectContext" may not actually exist. I don't know because I can't see you code. "self.managedObjectContext" is safe because that calls the accessor as it always has. – Tim Jun 28 '15 at 11:26
20

you should add this to your viewController:

 id delegate = [[UIApplication sharedApplication] delegate];
    self.managedObjectContext = [delegate managedObjectContext];
Hashem Aboonajmi
  • 8,866
  • 7
  • 54
  • 64
2

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.

rafaeljuzo
  • 379
  • 2
  • 8
2

In my case the .xcdatamodeld was mislabeled in the AppDelegate:

 let container = NSPersistentContainer(name: "name of data model")
0

If the destination view controller is embedded in a NavigationController, the context needs to be set appropriately as follows-

  self.mydetailViewController = [[[segue destinationViewController] viewControllers] objectAtIndex:0];
 [self.mydetailViewController setManagedObjectContext:self.managedObjectContext];
hackerinheels
  • 1,131
  • 1
  • 6
  • 13
0

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;
    }
SpaceTrucker
  • 1,128
  • 7
  • 16