3

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 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.

In application:didFinishLaunchingWithOptions:, I've put:

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

And in applicationWillTerminate::

[MagicalRecord cleanUp];

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.

Any ideas?

4

1 回答 1

13

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

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"];

于 2013-07-01T04:31:43.583 回答