在MagicalRecord中使用现有的SQLite数据库 [英] Using an existing SQLite database in MagicalRecord

查看:174
本文介绍了在MagicalRecord中使用现有的SQLite数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个SQLite数据库,其中包含来自某些JSON的记录,使用本教程,我想使用MagicalRecord查询它。

I've created a SQLite database that contains records from some JSON using this tutorial, and I want to use MagicalRecord to query it.

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

MagicalRecord sees the NSManagedObject (BlogPost) and can create records, but it doesn't see the prepopulated records, so I'm guessing it's not seeing the SQLite file I've added. I've verified that the SQLite database does indeed contain rows using a SQLite client.

应用程序:didFinishLaunchingWithOptions: ,我已经:

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

并且在 applicationWillTerminate:

[MagicalRecord cleanUp];

当我调用 [BlogPost MR_findAll] 一个控制器,它返回一个空集。 DBG.sqlite位于项目目录的根目录,我已经尝试把它放在复制Bundle资源,但 blogPosts 仍然返回一个空集。

When I call [BlogPost MR_findAll] in a controller, it returns an empty set. DBG.sqlite is at the root of the project directory, and I've tried putting it in "Copy Bundle Resources", but blogPosts still returns an empty set.

任何想法?

推荐答案

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

The issue ended up being that the preloaded SQLite db needs to be copied to the default path of the application's 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];

这篇关于在MagicalRecord中使用现有的SQLite数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆