Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

could not locate an NSManagedObjectModel for entity name

Tags:

This is the code for toggleAddProject method, the Core Data code is almost the same as found in Apple's CoreDataBooks sample, however when I click the add button the app crashes with entityForName: could not locate an NSManagedObjectModel for entity name 'Project' on the line starting with newProjectController.project

-(IBAction)toggleAddProject 
{
    NewProjectViewController *newProjectController = [[[NewProjectViewController alloc] initWithStyle:UITableViewStyleGrouped] autorelease];

    // Create a new managed object context for the new project -- set its persistent store coordinator to the same as that from the fetched results controller's context.
    NSManagedObjectContext *addingContext = [[NSManagedObjectContext alloc] init];
    self.addingManagedObjectContext = addingContext;
    [addingManagedObjectContext setPersistentStoreCoordinator:[[fetchedResultsController managedObjectContext] persistentStoreCoordinator]];
    newProjectController.project = (Project *)[NSEntityDescription insertNewObjectForEntityForName:@"Project" inManagedObjectContext:addingContext];
    [addingContext release];


    UINavigationController *addNewNavigationController = [[UINavigationController alloc] initWithRootViewController:newProjectController];
    [self.navigationController presentModalViewController:addNewNavigationController animated:YES];  
    [addNewNavigationController release];
}

Everything has been synthesized, the Project entity exists. I can't figure out why it crashes. Most people seem to be able to fix this error by inserting the following code either in the method itself, or in viewDidLoad:

if (managedObjectContext == nil) 
{ 
    managedObjectContext = [(CoreDataBooksAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext]; 
}

When modified for my app delegate it makes no difference. Thanks for any help.

like image 285
ChrisJP Avatar asked Jul 27 '10 21:07

ChrisJP


2 Answers

This error has only a few possible sources:

  1. Typo in the Entity name.
  2. Nil managed object context object.
  3. Failure to add the model containing the entity to the persistent store the context uses.
  4. Failure to add the correct persistent store to the context itself.
like image 61
TechZen Avatar answered Oct 16 '22 12:10

TechZen


I had this problem when I had several different NSManagedObjectContexts. The quick way to debug it was to inspect the different connection bits and make sure my entity was listed before calling the context.

NSLog(@"Context: %@",context);
NSLog(@"PS Coord : %@",context.persistentStoreCoordinator);
NSLog(@"MOM : %@", context.persistentStoreCoordinator.managedObjectModel);
NSLog(@"Entities : %@",[[context.persistentStoreCoordinator.managedObjectModel entities] valueForKey:@"name"]); 
like image 28
ghostfly Avatar answered Oct 16 '22 13:10

ghostfly