如何将现有的sqlite文件导入到Core Data中?

11
我需要将一个.sqlite文件导入Core Data中,我在互联网上搜索到了这篇文章:Core Data教程:如何预装/导入现有数据。它通过创建Python脚本来读取旧数据库的内容,并在新数据库中创建相应的行来填充该数据库。但是我的sqlite数据库在表和列的数量上太大了,这可能会花费我相当长的时间。
我还发现了另外一篇文章:在iPhone OS 3.0上使用预装SQLite数据库与Core Data。但是我不太理解它,它似乎是将旧数据库复制到新数据库中,然后如何为所有表和列名添加Z_后缀呢?此外,它要求我创建实体和属性,是否有自动从sqlite数据库文件中完成此操作的方式?
谢谢!

不,没有自动的方法。在Core Data之外创建的Sqlite数据库文件与其不兼容。 - alhcr
2个回答

2
这里的回答可能有用(我的回答是其中之一)
Pre-populate Core Data(预填充Core Data)的链接:Pre-populate Core Data
 /**
 Returns the path to the application's Documents directory.
*/
      - (NSString *)applicationDocumentsDirectory {
          return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,  NSUserDomainMask, YES) lastObject];
      }

示例代码


谢谢,但是[self applicationDocumentsDirectory] stringByAppendingPathComponent似乎不存在,我正在使用XCode 4.3。 - Heuristic
另外,我需要在执行你的代码之前先创建实体/属性吗?谢谢! - Heuristic
@hzxu 那个方法只是一个方便的方法,我刚刚编辑了我的问题以包含它。 - Oscar Gomez
@hzxu 是的,你必须定义实体,看一下我发布的示例代码。 - Oscar Gomez

0
// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the application's store added to it.
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (_persistentStoreCoordinator != nil)
    {
        return _persistentStoreCoordinator;
    }

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"yourSqlite.sqlite"];

    NSString *sourcePath = [[NSBundle mainBundle] pathForResource:@"yourSqlite.sqlite" ofType:nil];

    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSError *error = nil;

    if  (![[NSFileManager defaultManager] fileExistsAtPath:[documentsDirectory stringByAppendingPathComponent:@"yourSqlite.sqlite"] ]) {

        if([[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:[documentsDirectory stringByAppendingPathComponent:@"yourSqlite.sqlite"] error:&error]){
            NSLog(@"Default file successfully copied over.");
        } else {
            NSLog(@"Error description-%@ \n", [error localizedDescription]);
            NSLog(@"Error reason-%@", [error localizedFailureReason]);
        }
    }

    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error])
    {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    return _persistentStoreCoordinator;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接