2009-10-27 64 views
0

我想从一个sqlite文件(已使用核心数据与模型A创建)附加到我的应用程序使用的另一个sqlite存储(它使用相同的型号A)。这个想法是快速导入大量的数据。使用NSMigrationManager将数据追加到核心数据持久性存储

我面临的问题是下面的代码只能工作一次。当我尝试两次运行相同的代码时,应用程序将在我的评论标记的行中崩溃。任何帮助将不胜感激。

NSError **err; 
NSURL *importURL = [NSURL fileURLWithPath:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent: @"import.sqlite"]]; 
NSURL *storeURL = [NSURL fileURLWithPath:[[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"applicationdata.sqlite"]]; 
NSMigrationManager *migrator = [[NSMigrationManager alloc] initWithSourceModel:[self managedObjectModel] destinationModel:[self managedObjectModel]]; 
NSMappingModel *mappingModel = [NSMappingModel inferredMappingModelForSourceModel:[self managedObjectModel] destinationModel:[self managedObjectModel] error:err]; 
NSError **err2; 

// the following line crashes when the whole block is ran twice 
[migrator migrateStoreFromURL:importURL 
         type:NSSQLiteStoreType 
         options:nil 
      withMappingModel:mappingModel 
      toDestinationURL:storeURL 
       destinationType:NSSQLiteStoreType 
      destinationOptions:nil 
         error:err2]; 

NSLog(@"import finished"); 
[migrator release]; 

回答

1

我在代码中看到一个错误,它与该方法调用的错误参数有关。 NSError**意味着您要为该方法提供一个NSError*的地址,该地址将用于写出对错误对象的引用(如果发生错误)。现在你只是传入一个未初始化的指针,这个指针可能指向某个有效的指针,或者可能指向总的垃圾,这取决于当时栈上会发生什么。迁移者的方法将写入这一点,有时没有明显的不良影响,但有时会导致崩溃,就像您看到的那样。代码如下:

NSError *err2 = nil; //you want to initialize to nil, in case method doesn't modify your pointer at all (i.e. no error occurs) 

//the method also returns a BOOL indicating success/failure 
if (![migrator migrateStoreFromURL:importURL 
        type:NSSQLiteStoreType 
        options:nil 
     withMappingModel:mappingModel 
     toDestinationURL:storeURL 
      destinationType:NSSQLiteStoreType 
     destinationOptions:nil 
        error:&err2]) 
{ 
    //handle the error 
} 
0

感谢Brian指出了这一点。

最后我简单地增加额外的sqlite的文件堆栈的持久性存储,工作得很好,让我们以后限制fetchRequest将单个存储:

NSError *error = nil; 
NSURL *url = SOME_FILEPATH_URL; 
NSPersistentStore *newStore = [persistentStoreCoordinator 
            addPersistentStoreWithType:NSSQLiteStoreType 
               configuration:nil 
                  URL:url 
                 options:opt 
                 error:&error]; 

我们把所有persistentStores的字典供以后参考。

相关问题