Nikhil
Nikhil

Reputation: 379

This NSPersistentStoreCoordinator cannot perform a save operation

When I login the application it seems to crash at NSManagedObjectContext *managedObjectContext = self.managedObjectContext; in the following save context method and gives the error "This NSPersistentStoreCoordinator has no persistent stores (schema mismatch or migration failure). It cannot perform a save operation.",

- (BOOL) saveContext
{
    @synchronized (_localStorage) {
        //NSLog(@"----------------------------Save context called---------------------------");
        BOOL result = TRUE;
        NSError *error = nil;
        NSManagedObjectContext *managedObjectContext = self.managedObjectContext;

        if (managedObjectContext != nil)
        {
            if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error])
            {
                NSLog(@"----------------------------Save context failed---------------------------");
                result = FALSE;
                NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            }
        }

        //NSLog(@"----------------------------Save context completed---------------------------");

        return result;
    }
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
    {
        if (__persistentStoreCoordinator != nil)
        {
            return __persistentStoreCoordinator;
        }

        NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Badger.sqlite"];

        NSError *error = nil;
        __persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];

        NSDictionary *options = @{
                                  NSMigratePersistentStoresAutomaticallyOption : @YES,
                                  NSInferMappingModelAutomaticallyOption : @YES,
                                  NSSQLitePragmasOption : @{@"journal_mode" : @"DELETE"}
                                  };

        if(![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error])
        {
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        }

        return __persistentStoreCoordinator;
    }

Upvotes: 0

Views: 503

Answers (1)

Palanichamy
Palanichamy

Reputation: 96

Whenever we modify the data model of a Core Data application, the persistent store becomes incompatible with the data model and results in a crash. To fix this, we have to do data migration. For Core Data migration tutorial, please follow the below article. http://code.tutsplus.com/tutorials/core-data-from-scratch-migrations--cms-21844

Upvotes: 0

Related Questions