简体   繁体   中英

error with core data with nsmanagedobject context

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '+entityForName: could not locate an NSManagedObjectModel for entity name 'Persons'' *

The entity is created in the data model file and I added the core data functions to the app delegate file.

I am trying to use core data in in my first view controller which is in a tab by doing this:

- (IBAction)save:(id)sender {

NSLog(@"String is %d", [choiceSeg selectedSegmentIndex]);

NSManagedObjectContext *context = self.managedObjectContext;

Persons *person = (Persons *)[NSEntityDescription insertNewObjectForEntityForName:@"Persons" inManagedObjectContext:context];

NSNumber *ageValue = [NSNumber numberWithInt:[choiceSeg selectedSegmentIndex]];

[person setAge:ageValue];  

// Save the context
if (![context save:nil]) { 
    // error checking
}

Also, I did synthesize the managedObjectContext in my view.

What did I do wrong?

This error occurs when your instance of NSManagedObjectContext is nil. The recommended way of providing a context to a view controller is by passing by reference. To pass the context from your app delegate through a UITabBarController to the first view controller is fairly simple.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)options
{
    // Assuming you don't already have a property for this (i.e. setup by a storyboard)
    UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController;

    if (!tabBarController.viewControllers.count)
        return;

    FirstViewController *fvc = (FirstViewController *)[tabBarController.viewControllers objectAtIndex:0];

    // Assumes that this view controller has a public writable @property for a context.
    fvc.managedObjectContext = self.managedObjectContext;

    // ... [self.window makeKeyAndVisible]; etc...
}

I realize this isn't the greatest way to do it because tab bar items can be re-arranged and we're explicitly looking for the first one. It may be prudent to check the class of the returned view controller before attempting to set the context on it.

OK so I imported the AppDelegate.h into my view controller and used its managedObjectContext to enter an item in core data.

 AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *context = [appDelegate managedObjectContext];

It works!

I would like to know however if we have to import the delegate and get a local reference to the context every time we need to use core data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM