我的app reousrce-folder中有一个填充的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_;
}
答案 0 :(得分:2)
如果默认文件存在于documents文件夹中,则提供的代码将合并默认文件。如果在合并后删除该文件,则不应每次都加载该文件。您可以设置用户默认标志以记录以前是否已合并。
更好的解决方案是使用默认数据创建Core Data持久性存储,并将其包含在应用程序包中。首次启动时,将该文件复制到文档文件夹,然后将其分配给持久存储。该方法会更快,您不必担心合并失败。