I want to get the managed object context from AppDelegate, but the app crashed after I put the two lines of code into the method even I did nothing else, and there was a message in debug area:"CoreData: Cannot load NSManagedObjectModel. nil is an illegal URL parameter..."
The code added in my method:
AppDelegate *delegate = [UIApplication sharedApplication].delegate;
NSManagedObjectContext *managedObjectContext = delegate.managedObjectContext;
-managedObjectModel method in AppDelegate:
- (NSManagedObjectModel *)managedObjectModel {
// The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
if (_managedObjectModel != nil) {
return _managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"FoodPin" withExtension:@"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}
and the -managedObjectContext method:
- (NSManagedObjectContext *)managedObjectContext {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
if (_managedObjectContext != nil) {
return _managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (!coordinator) {
return nil;
}
_managedObjectContext = [[NSManagedObjectContext alloc]initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
return _managedObjectContext;
}
"FoodPin" is my project name.So what's wrong here?I'm new to iPhone programming (Core Data in particular).
Can anyone help me?
Thanks...
I had the same problem but for me the modelURL was correctly set. The problem was that my *.xcdatamodeld file was not in the Copy bundle ressources anymore. I don't know why it disappear but to add it again fix the problem.
Here is how to fix it : You project > Build Phases > Copy Bundle ressources > "+" button and select you xcdatamodeld file
The problem is this line:
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"FoodPin" withExtension:@"momd"];
modelURL
is nil
meaning that the system couldn't find the resource FoodPin.momd
.
Make sure you have a Core Data model in your project named FoodPin
. It will appear as FoodPin.xcdatamodeld
in the Project Navigator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With