Reputation: 1681
I have an existing database file. I want to use this db file in a project. I placed this file in my app folder in mac and dragged the same into Xcode. And now I have written the code to check whether the file exists or not. But it is throwing FALSE exception.
bool databaseAlreadyExists = [[NSFileManager defaultManager] fileExistsAtPath:@"school.db"];
Please let me know how to use the existing db files.
Thanks
Upvotes: 0
Views: 1928
Reputation: 11779
Try getting the path with
NSString *databasePath = [[NSBundle mainBundle] pathForResource:@"school" ofType:@"db"];
For Swift:
let dbPath = Bundle.main.path(forResource: "school", ofType: "db")
Upvotes: 2
Reputation: 4436
It depends on whether or not you need the database to be writable.
You can get access to the database just by doing this:
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"mydb.sqlite"];
but if you've copied it to another directory so you can write to it (e.g. the Documents directory), you'd need to do something like this to get the path:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"mydb.sqlite"];
Upvotes: 0
Reputation: 3055
I suppose you're using Core Data in your project, aren't you? If so take a look at the iPhone Core Data Recipes sample project by Apple! In the Classes/RecipesAppDelegate.m you'll find sample code for accomplishing what you need!
There's a good tutorial about pre-loading over at Ray Wenderlich's site. Shipping a pre-loaded database in the way the Core Data Recipes example showcases is not the most desireable way by Apple. So please take a look at the provided tutorial for a more sophisticated approach!
Upvotes: 0