2

我的应用程序资源文件夹中有一个填充的 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_;
}
4

1 回答 1

2

如果默认文件存在于文档文件夹中,所提供的代码将合并默认文件。如果在合并后删除文件,则不应每次都加载它。如果之前已合并,您可以设置用户默认标志来记录。

更好的解决方案是使用默认数据创建一个 Core Data 持久存储,并将其包含在应用程序包中。首次启动时,将该文件复制到文档文件夹,然后将其分配给持久存储。该方法会更快,您不必担心合并失败。

于 2010-12-05T15:46:25.917 回答