insertNewObjectForEntityForName:

Solution 1:

The fact that you didn't set up the MOC is almost certainly the problem. Most specifically, it means you're probably not loading your MOM (Managed Object Model) that defines Person. Somewhere in your code you should have something like this:

managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];    

And something like this:

persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];

And something like this:

NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
    managedObjectContext = [[NSManagedObjectContext alloc] init];
    [managedObjectContext setPersistentStoreCoordinator: coordinator];

I'm just copying lines out of the AppDelegate of the Core Data template (what you get if you make a new application that uses Core Data).

If you have all that, make sure that your xcdatamodel is listed in your Compile Sources step of the build. And of course make sure that Person is actually the Entity name in your xcdatamodel. Entity name is not the same as Class, though they are often set to be the same.

Solution 2:

You need the init of the Core Data

-(void)initCoreData{
        NSError *error;
        //Path to sqlite file.
        NSString *path = [NSHomeDirectory() stringByAppendingString:@"/Documents/Level4.sqlite"];
        NSURL *url = [NSURL fileURLWithPath:path];

        //init the model
        NSManagedObjectModel *managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];

        //Establish the persistent store coordinator
        NSPersistentStoreCoordinator *persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:managedObjectModel];

        if(![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:nil error:&error]){

                NSLog(@"Error %@",[error localizedDescription]);

        }else{
                self.context = [[[NSManagedObjectContext alloc ] init ] autorelease];
                [self.context setPersistentStoreCoordinator:persistentStoreCoordinator];
        }

        [persistentStoreCoordinator release];
}

Solution 3:

You should check if the NSManagedObjectContext object is nil.

e.g.

if (self.managedObjectContext == nil) {
    NSLog(@"NSManagedObjectContext is nil");
    return nil;
}