Using an existing SQLite database in MagicalRecord

2020-07-19 03:53发布

问题:

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?

回答1:

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.");
    }
}

This should be placed just before [MagicalRecord setupCoreDataStackWithStoreNamed:@"DBG.sqlite"];.