Reputation: 727
So I can access a read-only SQLite database inside an iPhone / iPod app (Objective-C), but I'm writing a new app that will have a writable database. Obviously, the r/w file has to be in the user-writable directory. My question is, should I ship an empty database with the application and copy it over to the r/w location, or create the r/w database on the fly the first time the app launches?
Upvotes: 2
Views: 1031
Reputation: 15099
You can do either, but it will be much easier (and less error prone) for you to create an empty database, put it in your bundle and then do this in your AppDelegate.m file:
- (void)prepareDatabase
{
//add Database Versioning check to see if the resources database is newer
// generally as simple as naming your database with a version on the end
NSFileManager *filemanager = [NSFileManager defaultManager];
NSString *databasePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingString:@"/YOURDATABASE.s3db"];
if(![filemanager fileExistsAtPath:databasePath]) {
//Database doesn't exist yet, so we copy it from our resources
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingString:@"/YOURDATABASE.s3db"];
if([filemanager copyItemAtPath:defaultDBPath toPath:databasePath error:nil]) {
NSLog(@"Database Copied from resources");
} else {
NSLog(@"Database copy FAILED from %@ to %@",defaultDBPath,databasePath);
}
}
}
Then in your applicationDidFinishLaunching:
method call this:
[self prepareDatabase];
Upvotes: 1