Using an existing SQLite database in MagicalRecord

纵饮孤独 提交于 2019-12-03 21:56:50

问题


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



来源:https://stackoverflow.com/questions/17351493/using-an-existing-sqlite-database-in-magicalrecord

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!