我的应用程序资源文件夹中有一个填充的 sqlite 数据库。在启动时,我想用这个 sqlite db 的数据预加载 coredata-store。我在persistantStoreCoordinator 方法中使用NSMigrationManager。这在第一次时效果很好,并将数据附加到存储中。但它会在每次启动时再次附加数据,因此在第二次启动后数据将被复制。我该如何解决这个问题?在数据库中我会使用主键,数据模型中是否有类似的东西?或者我可以比较实体对象吗?
感谢四位您的帮助,下面我使用的方法:
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (persistentStoreCoordinator_ != nil) {
return persistentStoreCoordinator_;
}
NSString *storePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"Raetselspass.sqlite"];
NSURL *storeUrl = [NSURL fileURLWithPath:storePath];
NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:@"Raetselspass" ofType:@"sqlite"];
NSURL *defaultStoreUrl = [NSURL fileURLWithPath:defaultStorePath];
/*
Set up the store.
For the sake of illustration, provide a pre-populated default store.
*/
// CANNOT USE THIS BELOW: WILL WORK ONCE, BUT WHEN I WILL UPDATE THE APP WITH
// NEW DATA TO APPEND, THEN THIS WILL NOT WORK
// NSFileManager *fileManager = [NSFileManager defaultManager];
// If the expected store doesn’t exist, copy the default store.
// if (![fileManager fileExistsAtPath:storePath]) {
// if (defaultStorePath) {
// [fileManager copyItemAtPath:defaultStorePath toPath:storePath error:NULL];
// }
// }
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
persistentStoreCoordinator_ = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [self managedObjectModel]];
NSError *error;
if (![persistentStoreCoordinator_ addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:options error:&error]) {
// Update to handle the error appropriately.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort(); // Fail
}
//migration
rror:&error];
NSError *err = nil;
NSMigrationManager *migrator = [[NSMigrationManager alloc] initWithSourceModel:[self managedObjectModel] destinationModel:[self managedObjectModel]];
NSMappingModel *mappingModel = [NSMappingModel inferredMappingModelForSourceModel:[self managedObjectModel] destinationModel:[self managedObjectModel] error:&err];
NSError *err2;
if (![migrator migrateStoreFromURL:defaultStoreUrl
type:NSSQLiteStoreType
options:nil
withMappingModel:mappingModel
toDestinationURL:storeUrl
destinationType:NSSQLiteStoreType
destinationOptions:nil
error:&err2])
{
//handle the error
}
NSLog(@"import finished");
[migrator release];
return persistentStoreCoordinator_;
}