【问题标题】:How to import a pre-existing sqlite file into Core Data?如何将预先存在的 sqlite 文件导入 Core Data?
【发布时间】:2011-09-28 10:53:25
【问题描述】:

我需要将一个.sqlite文件导入Core Data,我在网上搜索发现:

Core Data Tutorial: How To Preload/Import Existing Data

它正在创建一个 Python 脚本,通过读取旧数据库的内容来填充这个数据库,并在新数据库中创建适当的行。但是我的sqlite数据库的表和列的数量太大了,这可能会花费我相当多的时间。

我还发现了这个:

Using a Pre-Populated SQLite Database with Core Data on iPhone OS 3.0

但是我不是很明白,好像是把旧的数据库复制到一个新的,那它是怎么给所有的表名和列名加上Z_后缀的呢?另外,它要求我创建实体和属性,这是否可以自动完成(来自 sqlite dabase 文件)?

谢谢!

【问题讨论】:

  • 不,没有任何自动方式。在 Core Data 之外创建的 Sqlite 数据库文件与它不兼容。

标签: iphone ios sqlite core-data


【解决方案1】:

这里的答案可能有用(我的就是其中之一)

Pre-populate Core Data

 /**
 Returns the path to the application's Documents directory.
*/
      - (NSString *)applicationDocumentsDirectory {
          return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,  NSUserDomainMask, YES) lastObject];
      }

sample code

【讨论】:

  • 谢谢,但 [self applicationDocumentsDirectory] ​​stringByAppendingPathComponent 似乎不存在,我使用的是 XCode 4.3
  • 另外,在执行代码中显示的操作之前,我是否需要先创建实体/属性?谢谢!
  • @hzxu 该方法只是一种方便的方法,我只是编辑了我的问题以包含它。
  • @hzxu 是的,你必须定义实体,看看我发布的示例代码。
【解决方案2】:
// 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-23
    • 2018-07-02
    • 1970-01-01
    • 2012-04-25
    • 2012-10-29
    • 2019-01-19
    • 1970-01-01
    相关资源
    最近更新 更多