I am working on a application in which we are using x.x.xcdatamodel. Now in same x.x.xcdatamodel I have added an attribute in one of the entity. The application crashes showing the message "This NSPersistentStoreCoordinator has no persistent stores (schema mismatch or migration failure). It cannot perform a save operation.". I tried many things and i am also using lightweight migration to handle the situation but that is not working as well.Below is my code:
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (__persistentStoreCoordinator != nil)
{
return __persistentStoreCoordinator;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"myApp.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;
}
- (BOOL) saveContext
{
@synchronized (_localStorage) {
//NSLog(@"----------------------------Save context called---------------------------");
BOOL result = TRUE;
NSError *error = nil;
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil)
{
//Crashes here at this line.
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error])
{
NSLog(@"----------------------------Save context failed---------------------------");
result = FALSE;
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
}
}
//NSLog(@"----------------------------Save context completed---------------------------");
return result;
}
}
Am i missing something over here? OR Is it like i have to perform complete migration even if i add a single attribute in an entity?Thanks in advance.
You don't have to do the migration yourself here. You do have to add a new version of the data model. You can't edit the xcdatamodel
and expect Core Data to just use the new version. You need to keep your existing model, create a new version, and make your changes in the new version. You must always have a version of the model that matches the persistent store file.
You create a new version by selecting the xcdatamodel
model file in Xcode's file browser, going to the "Editor" menu, and selecting "Add Model Version..."