Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Cannot load NSManagedObjectModel. nil is an illegal URL parameter"

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...

like image 926
ZyusAn Avatar asked Oct 06 '15 10:10

ZyusAn


2 Answers

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

like image 111
Tom Giraudet Avatar answered Oct 29 '22 14:10

Tom Giraudet


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.

like image 26
Steve Wilford Avatar answered Oct 29 '22 14:10

Steve Wilford