Reputation: 17339
I copied a filled, existing sqlite3-file to my project; it is found (I check that with
- (void)createEditableCopyOfDatabaseIfNeeded {
NSLog(@"Checking if we have to create editable copy of database");
// First, test for existence.
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"hvw.sqlite"];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success) return;
NSLog(@"Creating editable copy of database");
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"hvw.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
}
}
I do not come to the "Creating editable copy of database"-part, so the file is there and found.
But my fetch does not return any results:
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Game" inManagedObjectContext:managedObjectContext];
[request setEntity:entity];
NSError *error;
NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
No error is thrown, but the resulting array is empty...
edit
I replaced the line
NSString *documentsDirectory = [paths objectAtIndex:0];
by
NSString *documentsDirectory = [self applicationDocumentsDirectory];
and in the log file I see error while trying to save or read objects:
Operation could not be completed. (Cocoa error 256.)
Upvotes: 2
Views: 368
Reputation: 170319
Was this SQLite database created using Core Data? You can't just use any SQLite database you want for your persistent store, it has to have the exact internal format that Core Data uses.
If this is a standard SQLite database that you want to bring across to Core Data, my recommendation is to write a migration method that takes in the SQLite and creates Core Data managed objects from that, setting up all of the appropriate relationships. When the migration operation has completed, you can write out the resulting persistent store to disk and use it for Core Data within your application from then on. If you're more adventurous, you can have this migration take place on a background thread, passing notifications to add managed objects to the main thread's managed object context as they are parsed from SQLite.
Upvotes: 1