'+entityForName: nil is not a legal NSManagedO

2020-01-26 03:45发布

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.

8条回答
家丑人穷心不美
2楼-- · 2020-01-26 04:16

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.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2020-01-26 04:18

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

查看更多
登录 后发表回答