Me estaba arrancando el pelo por el error "No se puede encontrar el modelo para la tienda de origen" durante todo un día. Aquí es una elaboración de la respuesta de learner2010 para que los Googlers: Modelo de hash
Su base de datos SQLite debe coincidir con uno de la mamá o momd creado por su xcdatamodel cuando se genera la aplicación. Puede ver los valores hash en el VersionInfo.plist de momd en el paquete de la aplicación creada. Vea a continuación el código para encontrar el hash de modelo de su base de datos.
Así que si cambia su xcdatamodel en lugar de crear una nueva versión en Xcode-> Editor-> Agregar versión de modelo ... entonces el hash de su modelo será diferente, y addPersistentStoreWithType no podrá usar su base de datos anterior , que usó el viejo modelo. Eso es lo que causa el error "No se puede encontrar el modelo para la tienda de origen".
Para empeorar las cosas, la base de datos sqlite se almacena en algo como "/ private/var/mobile/Library/Mobile Documents/YOU_APP_ID/Data.nosync/YOUR_DB.sqlite" y esto puede mantenerse incluso si elimina la aplicación desde el dispositivo y vuelva a instalarlo! Entonces pensarás que hay algo mal con tu código, cuando en realidad solo tienes una base de datos obsoleta que necesita ser eliminada.Por lo general, esto ocurre durante la depuración, por lo que no hay datos reales de todos modos.
Por lo tanto, el flujo de trabajo adecuado para permitir migraciones en el futuro es hacer su modelo, ejecutar su aplicación para construir la base de datos y luego crear NUEVAS VERSIONES del modelo cada vez que necesite realizar cambios. Todo "solo funcionará" si mantiene los cambios menores. Luego, cuando esté listo para lanzar su aplicación, seleccione el modelo final y elimine el resto. A continuación, elimine su base de datos de "/ private/var/mobile/Library/Mobile Documents". Luego, en versiones futuras, incluya todos los modelos de versiones anteriores junto con su modelo más reciente (si ha cambiado) y los usuarios podrán migrar cada vez.
Aquí está mi código hasta ahora. La línea importante es:
[fileManager removeItemAtPath:iCloudData error:&error];
Pero solo se utilizará durante la depuración para eliminar su base de datos anterior. Aquí está el código de producción en AppDelegate.m:
- (NSManagedObjectModel *)managedObjectModel
{
if (__managedObjectModel != nil)
{
return __managedObjectModel;
}
//NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Model" withExtension:@"momd"];
//__managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
//NSArray *testArray = [[NSBundle mainBundle] URLsForResourcesWithExtension:@"momd"subdirectory:nil];
NSString *path = [[NSBundle mainBundle] pathForResource:@"Model" ofType:@"momd"];
if(!path) path = [[NSBundle mainBundle] pathForResource:@"Model" ofType:@"mom"];
NSURL *modelURL = [NSURL fileURLWithPath:path];
__managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
//__managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];
return __managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if((__persistentStoreCoordinator != nil)) {
return __persistentStoreCoordinator;
}
__persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [self managedObjectModel]];
NSPersistentStoreCoordinator *psc = __persistentStoreCoordinator;
// Set up iCloud in another thread:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// ** Note: if you adapt this code for your own use, you MUST change this variable:
NSString *iCloudEnabledAppID = @"RW6RS7HS69.com.zsculpt.soaktest";
// ** Note: if you adapt this code for your own use, you should change this variable:
NSString *dataFileName = @"mydailysoak.sqlite";
// ** Note: For basic usage you shouldn't need to change anything else
NSString *iCloudDataDirectoryName = @"Data.nosync";
NSString *iCloudLogsDirectoryName = @"Logs";
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *localStore = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:dataFileName];
NSURL *iCloud = [fileManager URLForUbiquityContainerIdentifier:nil];
if (iCloud) {
NSLog(@"iCloud is working");
NSURL *iCloudLogsPath = [NSURL fileURLWithPath:[[iCloud path] stringByAppendingPathComponent:iCloudLogsDirectoryName]];
NSLog(@"iCloudEnabledAppID = %@",iCloudEnabledAppID);
NSLog(@"dataFileName = %@", dataFileName);
NSLog(@"iCloudDataDirectoryName = %@", iCloudDataDirectoryName);
NSLog(@"iCloudLogsDirectoryName = %@", iCloudLogsDirectoryName);
NSLog(@"iCloud = %@", iCloud);
NSLog(@"iCloudLogsPath = %@", iCloudLogsPath);
if([fileManager fileExistsAtPath:[[iCloud path] stringByAppendingPathComponent:iCloudDataDirectoryName]] == NO) {
NSError *fileSystemError;
[fileManager createDirectoryAtPath:[[iCloud path] stringByAppendingPathComponent:iCloudDataDirectoryName]
withIntermediateDirectories:YES
attributes:nil
error:&fileSystemError];
if(fileSystemError != nil) {
NSLog(@"Error creating database directory %@", fileSystemError);
}
}
NSString *iCloudData = [[[iCloud path]
stringByAppendingPathComponent:iCloudDataDirectoryName]
stringByAppendingPathComponent:dataFileName];
NSLog(@"iCloudData = %@", iCloudData);
NSMutableDictionary *options = [NSMutableDictionary dictionary];
[options setObject:[NSNumber numberWithBool:YES] forKey:NSMigratePersistentStoresAutomaticallyOption];
[options setObject:[NSNumber numberWithBool:YES] forKey:NSInferMappingModelAutomaticallyOption];
[options setObject:iCloudEnabledAppID forKey:NSPersistentStoreUbiquitousContentNameKey];
[options setObject:iCloudLogsPath forKey:NSPersistentStoreUbiquitousContentURLKey];
[psc lock];
NSError *error;
[psc addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:[NSURL fileURLWithPath:iCloudData]
options:options
error:&error];
if(error)
{
NSLog(@"Error adding persistent store %@, %@", error, [error userInfo]);
// comment in this line while debugging if get "Can't find model for source store" error in addPersistentStoreWithType.
// it means the sqlite database doesn't match the new model and needs to be created from scratch.
// this happens if you change the xcdatamodel instead of creating a new one under Xcode->Editor->Add Model Version...
// CoreData can only automatically migrate if there is a new model version (it can't migrate if the model simply changes, because it can't see the difference between the two models).
// be sure to back up the database if needed, because all data will be lost.
//[fileManager removeItemAtPath:iCloudData error:&error];
/*// this is another way to verify the hashes for the database's model to make sure they match one of the entries in the momd directory's VersionInfo.plist
NSDictionary *sourceMetadata = [NSPersistentStoreCoordinator metadataForPersistentStoreOfType:NSSQLiteStoreType URL:[NSURL fileURLWithPath:iCloudData] error:&error];
if(!sourceMetadata)
NSLog(@"sourceMetadata is nil");
else
NSLog(@"sourceMetadata is %@", sourceMetadata);*/
}
[psc unlock];
}
else {
NSLog(@"iCloud is NOT working - using a local store");
NSMutableDictionary *options = [NSMutableDictionary dictionary];
[options setObject:[NSNumber numberWithBool:YES] forKey:NSMigratePersistentStoresAutomaticallyOption];
[options setObject:[NSNumber numberWithBool:YES] forKey:NSInferMappingModelAutomaticallyOption];
[psc lock];
NSError *error;
[psc addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:localStore
options:options
error:nil];
if(error)
NSLog(@"Error adding persistent store %@, %@", error, [error userInfo]);
[psc unlock];
}
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:@"SomethingChanged" object:self userInfo:nil];
});
});
return __persistentStoreCoordinator;
}
Usted puede simplemente eliminar la aplicación para el teléfono y vuelva a instalar y se obtiene una aplicación fresca y por lo tanto una tienda sqlite fresca – thelaws