【问题标题】:Using an existing SQLite database in MagicalRecord在 MagicalRecord 中使用现有的 SQLite 数据库
【发布时间】:2013-06-25 10:43:42
【问题描述】:

我使用this tutorial 创建了一个包含来自某些 JSON 记录的 SQLite 数据库,我想使用 MagicalRecord 对其进行查询。

MagicalRecord 看到 NSManagedObject (BlogPost) 并可以创建记录,但它没有看到预填充的记录,所以我猜它没有看到我添加的 SQLite 文件。我已经使用 SQLite 客户端验证了 SQLite 数据库确实包含行。

application:didFinishLaunchingWithOptions: 中,我输入了:

[MagicalRecord setupCoreDataStackWithStoreNamed:@"DBG.sqlite"];

applicationWillTerminate::

[MagicalRecord cleanUp];

当我在控制器中调用[BlogPost MR_findAll] 时,它返回一个空集。 DBG.sqlite 在项目目录的根目录下,我试过把它放在“复制捆绑资源”中,但blogPosts 仍然返回一个空集。

有什么想法吗?

【问题讨论】:

  • 您的 SQLite 文件是否已连接到您的核心数据模型定义?你是如何创建它的?
  • 我使用问题中链接的教程创建了它。 (基本上,我制作了一个命令行工具,它在我的主应用程序(问题中描述的应用程序)中使用 Core Data 模型将 JSON 转换为 Core Data 记录,然后将生成的 SQLite 文件复制到我的主应用程序中。)我错了吗假设setupCoreDataStackWithStoreNamed: 是将Core Data 连接到现有数据存储的方式?
  • 生成 sqlite 文件后,您是否以任何方式更改模型?
  • 不,根本没碰过。
  • 默认情况下,MR 会进行大量日志记录,因此如果出现问题,应该有一些线索。通常(在调试模式下)如果您提供的 sqlite 文件与数据模型版本不匹配,它将被删除。

标签: objective-c core-data magicalrecord


【解决方案1】:

问题最终是需要将预加载的 SQLite db 复制到应用程序 db 的默认路径:

NSArray *paths = [[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
NSURL *documentPath = [paths lastObject];

NSURL *storeURL = [documentPath URLByAppendingPathComponent:@"DBG.sqlite"];

if (![[NSFileManager defaultManager] fileExistsAtPath:[storeURL path]]) {
    NSURL *preloadURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"DBG" ofType:@"sqlite"]];
    NSError* err = nil;

    if (![[NSFileManager defaultManager] copyItemAtURL:preloadURL toURL:storeURL error:&err]) {
        NSLog(@"Error: Unable to copy preloaded database.");
    }
}

这应该放在[MagicalRecord setupCoreDataStackWithStoreNamed:@"DBG.sqlite"];之前。

【讨论】:

  • 在我将setupCoreDataStackWithStoreNamed 更改为setupCoreDataStackWithAutoMigratingSqliteStoreNamed 之前,上述解决方案不适用于预填充核心数据
猜你喜欢
  • 2014-11-02
  • 1970-01-01
  • 1970-01-01
  • 2019-09-01
  • 2013-03-14
  • 1970-01-01
  • 1970-01-01
  • 2012-11-02
  • 2019-04-14
相关资源
最近更新 更多