Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an existing SQLite database in 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 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?

like image 857
Tom Avatar asked May 18 '26 02:05

Tom


1 Answers

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

like image 198
Tom Avatar answered May 21 '26 15:05

Tom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!