How to specify path for sqlite db in iPhone project?

After adding as a resource, the database file itself is located in the root of the project.

I managed to open it, indicating the full path, as OS X sees it, i.e. "/ Users / Louis / Documents / Test Project / test.db".

But, of course, there is no such way on the iPhone.

I think I should define the path as "application root / test.db", but I don’t know how to do this, or if it worked even in a place other than my development machine.

Thanks for any ideas.

+4
source share
3 answers

To get the path to the file you added to Xcode, you should use pathForResource: ofType: with your mainBundle.

NSString *path = [[NSBundle mainBundle] pathForResource:@"yourDb" ofType:@"sqlite"]; 

But you cannot modify files in mainBundle. Therefore, you need to copy it to another place. For example, in the library of your application.

You can do it as follows:

 NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject]; NSString *targetPath = [libraryPath stringByAppendingPathComponent:@"yourDB.sqlite"]; if (![[NSFileManager defaultManager] fileExistsAtPath:targetPath]) { // database doesn't exist in your library path... copy it from the bundle NSString *sourcePath = [[NSBundle mainBundle] pathForResource:@"yourDb" ofType:@"sqlite"]; NSError *error = nil; if (![[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:targetPath error:&error]) { NSLog(@"Error: %@", error); } } 
+8
source

Do not use the SQLite API, use this wonderful shell called FMDB: https://github.com/ccgus/fmdb

+1
source

Source: https://habr.com/ru/post/1340329/


All Articles