开发者

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.sql开发者_StackOverflowite"];

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?


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


What you mean by "comparing" the two paths?

What I see is a file copy from your app resources directory to the user document directory.

So what is happening is that a default version of Sports.sqlite that is to be bundled with the app (and thus is available in the resources directory) is copied to the user directory where the user can modify it.

The first chunk of code simply build the destination path (a string); the second chunk build the source path (a string) and then makes the copy.

Does it make sense?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜