When you include the database into your bundle via Xcode's "Copy Bundle Resources", it's part of the bundle, i.e. you get the path via:
NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"DataBase" ofType:@"sqlite"];
If you want to copy that to your Documents folder so that you can use it, you get the Documents path via:
NSString *documentsFolder = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *documentsPath = [documentsFolder stringByAppendingPathComponent:@"DataBase.sqlite"];
So, you might check for existence in Documents, and if not there, copy from bundle to Documents:
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:documentsPath]) {
NSError *error = nil;
BOOL success = [fileManager copyItemAtPath:bundlePath toPath:documentsPath error:&error];
NSAssert(success, @"%s: copyItemAtPath failed: %@", __FUNCTION__, error);
}
You can now open the database in the Documents folder (e.g. using documentsPath
).
Now, if you ever attempted to open a database in Documents without first copying from the bundle, the standard sqlite3_open
will create a blank database. So, you probably want to delete the app from the device/simulator and then reinstall, to get rid of that blank database in Documents (otherwise the above logic, testing for the existence of the database in Documents, will result in false positive).