Ali
Ali

Reputation: 11600

NSInternalInconsistencyException while adding Core Data into an application

I am adding Core Data into an existing application, I am following these steps:

In addition to set up the stack, I'm using the following code:

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

    return managedObjectContext;
}

- (NSManagedObjectModel *)managedObjectModel {
    if (managedObjectModel != nil) {
        return managedObjectModel;
    }
    managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];

    return managedObjectModel;
}

-(NSPersistentStoreCoordinator *)persistentStoreCoordinator {

    if (persistentStoreCoordinator != nil) {
        return persistentStoreCoordinator;
    }

    NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"xxxxx.sqlite"]];

    NSError *error = nil;
    persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [self managedObjectModel]];
    if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error]) {
       // Handle error
    }    

    return persistentStoreCoordinator;
}

- (NSString *)applicationDocumentsDirectory {
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}

But when I am trying to save data I get the following execption

Terminating app due to uncaught exception NSInternalInconsistencyException, reason: 'This NSPersistentStoreCoordinator has no persistent stores. It cannot perform a save operation.'

Upvotes: 1

Views: 3185

Answers (1)

Lorenzo B
Lorenzo B

Reputation: 33428

This problem could be do to the fact you have run the application and then you have changed the model.

The simplest solution is to delete the application from the simulator/device, then performing a Clean, and trying again.

The more correct solution is to deal with light migration as suggested in I keep on getting "save operation failure" after any change on my XCode Data Model.

A simple suggestion is to enable Core Data logs as suggested in XCode4 and Core Data: How to enable SQL Debugging and see what is going under the hood.

Hope that helps.

Upvotes: 4

Related Questions