I have created a core data database in one application which involved sucking out info from an API and populating a database.
I would now like to use it in another app.
I have copied the .xcdatamodeld file and NSManagedObject classes across.
I have added and imported Core Data framework.
I have copied the .sqlite file into my new application’s resources as the default database.
I am using the following code which is supposed to copy out the default database to the Documents directory and open it so that I may perform queries on it.
It is causing the app to crash with no error message, any thoughts on where I’m going wrong?
If I was to create a database here using saveToURL, I know the filename would be persistentStore not Trailer.sqlite as per below, is that relevant?
Thanks
- (void)viewDidLoad
{
[super viewDidLoad];
// Get URL -> "<Documents Directory>/<TrailerDB>"
NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
url = [url URLByAppendingPathComponent:@"TrailerDB"];
UIManagedDocument *doc = [[UIManagedDocument alloc] initWithFileURL:url];
// Copy out default db to documents directory if it doesn't already exist
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:[url path]]) {
NSString *defaultDB = [[NSBundle mainBundle]
pathForResource:@"trailerdatabase" ofType:@"sqlite"];
if (defaultDB) {
[fileManager copyItemAtPath:defaultDB toPath:[url path] error:NULL];
}
}
if (doc.documentState == UIDocumentStateClosed) {
// exists on disk, but we need to open it
[doc openWithCompletionHandler:^(BOOL success)
{
if (success) [self useDatabase:doc];
if (!success) NSLog(@"couldn’t open document at %@", url);
}];
} else if (doc.documentState == UIDocumentStateNormal)
{
[self useDatabase:doc];
}
}
Ive had another look and I’m not sure what you’re doing but this code below is what i do that would answer your question. I check to see if the working database exists and if it doesn’t i move it in place from the application bundle and then proceed to load it. I have left the stock comments from the Apple template in as i think they may end up being helpful.