Search code examples
objective-csqlitensbundlensdocumentdirectory

NSDocumentDirectory or NSBundle resourcePath with Sqlite?


i was wondering why we search a path with NSDocumentDirectory at first here :

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);  
NSString *documentsDirectory = [paths objectAtIndex:0];  
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"Sports.sqlite"];

and later on we compare this path with another path, using this time resourcePath from the NSBundle :

NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] 
                                        stringByAppendingPathComponent:@"Sports.sqlite"];  
success = [fileManager copyItemAtPath:defaultDBPath
                               toPath:writableDBPath error:&error];

What is the difference between both?


Solution

  • In this situation you are (normally one time only, unless you need to restore database) copying the database from your read only bundle into your documents directory so that a user can read/write to it. This is useful if you want to pre-seed a database or just have the structure set up.

    Your documents directory is read/write and your bundle is not therefore you need to have the sqlite in your documents directory for it to be used properly.

    1. The first part of code is simply getting you the path for where you want the sqlite file to live in your documents directory. Which ends up being held in writableDBPath.

    2. Next you get the path from your bundle (defaultDBPath) and use the two paths to

      ... copyItemAtPath:defaultDBPath toPath:writableDBPath ...
      

    This gives you a read/write database that you provide in your bundle. Why would you do this instead of running your SQL on the device to create the schema? This allows you to pre-seed the database with some data. It can sometimes be easier to use a graphical tool to set up and edit your sqlite file