Search code examples
core-dataentitynsmanagedobjectcontext

+entityForName: could not locate an NSManagedObjectModel for entity name 'Ditloide' in a second view


I try to explain my problem.

I have a first view in which I have some buttons. Pressing a button the app open a tableview. I have those files in my project:

  • AppDelegate.h/m
  • viewcontroller.h/m to control the first view
  • Entity1TableViewController.h/m to control the tableview opened by that
    button in 1st view
  • an .xcdatamodel

so, until I'm in the tableview all is right. I putted this

 NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
 NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity];
 NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:@"Ditloide" inManagedObjectContext:context]; 

and when I tab on the button I receive the error:

+entityForName: could not locate an NSManagedObjectModel for entity name 'Ditloide' in a second view

I read other posts in which I found something like this:

MainViewController *controller = (MainViewController *)self.window.rootViewController;
controller.managedObjectContext = self.managedObjectContext;

to put in the rootcontroller. but in my case, where can I put this? I have to create a new controller? if yes, I cant insert the

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

method.

So, how can I solve the problem?


Solution

  • I'm not pretty sure I understand your question.

    The error is due to the fact you didn't set up the MOC correctly. See insertNewObjectForEntityForName: for further details.

    The question is: did you set up the core data stack correctly? Could you share some code?

    Then, about the code you have seen, it has the goal to inject the context wherever it is needed. For example, suppose you have a controller, called YourController, that needs the context. You can create a property in YourController like the following:

    //.h
    @property (nonatomic, retain) NSManagedObjectContext* context; // or strong if you ARC
    
    //.m
    @synthesize context;
    

    Then, from a different element, for example the app delegate (if you have set up the core data stack there), you could just create YourController and inject it.

    YourController* yourCtr = // alloc-init
    yourCtr.context = [self managedObjectContext];
    

    Finally, what do you mean with if yes, I cant insert the - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions method?