I am using following code to copying database file to other folder just to make temporary writing file.
BOOL success;
NSArray*dirPath;
NSString*docDir;
NSString*databasePath;
NSString*databaseName=@"EXPENSES";
//path for database
dirPath=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docDir=[dirPath objectAtIndex:0];
databasePath=[docDir stringByAppendingPathComponent:databaseName];
NSLog(@" docDir %@",docDir);
//check if present
NSFileManager*fm=[NSFileManager defaultManager];
success=[fm fileExistsAtPath:databasePath];
if(success)
{
NSLog(@"DATA BASE Already present");
}
else
{
//Copy from bundle to DocumentsDirectory on first run. Where DB won't be available in DocumentsDirectory.
NSString*bundlePath=[[NSBundle mainBundle] pathForResource:@"EXPENSES" ofType:@""];
NSError*error;
success=[fm copyItemAtPath:bundlePath toPath:databasePath error:&error];
if(success)
{
NSLog(@"DATA BASE Created successfully");
}
} // End of else when DB not present in documents directory.
But the file is not copying instead app is crashing with error “reason: ‘* -[NSFileManager copyItemAtPath:toPath:error:]: source path is nil'” please help me to debug the code Thank you
You are doing two mistakes here.
You didn’t mentioned your destination file extension
Instead of
NSString*databaseName=@"EXPENSES";Use
NSString*databaseName=@"EXPENSES.sqlite";This code is the actual issue:
Here you are telling to
NSFileManagerthat find the file with name"EXPENSES"and it’s extension is""probably there will be no file with these criteria. So the source path’ll benil. That’s why the application is crashing.Usually the extension of database file will be
sqlite. Replace your code like: