I just started with iPhone development. In one of the example where I had to display some data stored in sqlite db in a table view in a tabbar controller, I had to move a sqlite file from application bundle to the documents folder.
I used the application template – iOS > Application > Window-based application for iPhone (Used core data for storage)
In the template generated by XCode (base sdk set to latest iOS = 4.2), the following code was there…
- (NSURL *)applicationDocumentsDirectory {
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
In trying to get a path to documents folder, I used the method given above like this…
NSString *documentDirectory = [self applicationDocumentsDirectory];
This gave a warning – warning: incompatible Objective-C types initializing 'struct NSURL *', expected 'struct NSString *'
So I changed the code to following…
// Added the message absoluteString over here
NSString *documentDirectory = [[self applicationDocumentsDirectory] absoluteString];
NSString *writableDBPath = [documentDirectory stringByAppendingPathComponent:@"mydb.sqlite"];
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"mydb.sqlite"];
BOOL success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
NSLog(@"Failed to create writable database file with message '%@'.", [error localizedDescription]);
}
And BOOM!!! It gave the error that – 'Failed to create writable database file with message 'The operation couldn’t be completed. No such file or directory'.'
How should I find the path to documents directory since the method applicationDocumentsDirectory generated by XCode template does not work for me.
Also, can somebody throw some light on the purpose of applicationDocumentsDirectory method given above.
Thanks
I just ran into this myself a few days ago. Don’t force things down the Path path, embrace the NSURL path. It won’t take but a short time to get how to use them.
As to the method, it’s simply asking the system to hand you a URL to the standardized documents directory for the application. Use this and most everything regarding where you put new files will be correct.