Search code examples
objective-ciossqlitefmdb

Create database file if not exist


I'm trying to create database file in first application's launch. Used FMDB library. For this purpose I'm checking if database file already exist, if not I want to copy database file from project. My code:

-(void)checkAndCreateDatabase {
NSLog(@"check and create database doing");
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *dbFileName = [docDir stringByAppendingPathComponent:@"FriendsDatabase.sqlite3"];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;

if (![fileManager fileExistsAtPath:dbFileName]) {
    [fileManager copyItemAtPath:[[NSBundle mainBundle] pathForResource:@"FriendsDatabase" ofType:@"sqlite3"] toPath:dbFileName error:&error];
    NSLog(@"database created");
} else {
    NSLog(@"fail to create database");
}

FMDatabase  *_db = [[FMDatabase alloc] initWithPath: dbFileName];
if (![_db open]) {
    [_db release];
    NSLog(@"Could't open DB");
    }
_db.logsErrors = NO;

self.db = _db;
[_db release];
}

But I have an error: 'NSInvalidArgumentException', reason: '*** -[NSFileManager copyItemAtPath:toPath:error:]: source path is nil'. What I'm doing wrong?


Solution

  • It looks like you don't have a file named "FriendsDatabase.sqlite3" in your main bundle. (If you had one, the source path in your call to -copyItemAtPath:toPath:error: wouldn't be nil.)

    Try changing your code to look like:

    NSString *path = [[NSBundle mainBundle] pathForResource:@"FriendsDatabase" ofType:@"sqlite3"];
    [fileManager copyItemAtPath:path toPath:dbFileName error:&error];
    

    Then step through the code with your debugger and check the value of path.

    Note that you've specified "FriendsDatabase" (note the 's') as the name of the file in your code, but your comment calls the file "FriendDatabase". Perhaps you've just misspelled the filename in your code -- that's a good reason to use constants!