Code Snippet – Quickly Find The Documents Directory

  • Twitter
  • Facebook
  • Digg
  • Reddit
  • StumbleUpon
  • del.icio.us
  • Google Bookmarks
September 9th, 2009 Posted by: (ELC) - posted under:Snippets

As many of you may have seen by now, there are quite a few ways to find the documents directory on the iPhone.  For those of you who don’t know, the documents directory of an app is the location where you should save your application data.  While finding the documents directory is a trivial task, it is very important when coding most applications.  Apple has provided quite a few ways for resolving the path to this directory.

If you read through some of Apple’s sample code, you will see their code to do this is generally 3 or 4 lines long.  This seems like a lot of code to perform such a simple task.  Here is a nice one-liner for you to use in your applications.

NSString * docs = [NSHomeDirectory()
						   stringByAppendingPathComponent:@"Documents"];

It’s clean and concise. Happy iCoding!

  • http://Alblue.blogspot.com Alex Blewitt

    Which of course fails to work on non-English platforms as the “Documents” directory is localised to the language in question and is not always “Documents” therefore.

  • http://formulas-app.com Reese

    I would tend to go with how apple does it rather than this way. There is usually a method to their madness.

  • http://brandontreb.com Brandon

    @Alex – Are you sure? Apple renames the documents directory of an app based on the language?

  • Michael

    The name of the directory will be the same for all languages. Only the display name is translated to the selected locale. But, there is no way to be sure that the name of the directory will be always “Documents” for all versions of the os. So, hardcoding such values is always a bad idea.

  • layne

    any ideas on how to test if a file exists? I download files store them to a path I create by using.

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"csv.txt"];

    I would like to know if csv.txt is already there.

    Thanks

  • layne

    I tried the following but it did work for me

    FILE* testFile = fopen(path, “rb”);
    if (testFile) {
    NSLog(@”found file”);
    }

  • squidbot

    Here’s the proper one-liner:

    [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]

  • rey

    @Michael

    “But, there is no way to be sure that the name of the directory will be always “Documents” for all versions of the os.” Are you serious? Renaming the Documents directory in an OS iteration sounds very Microsoft. Why would anyone do that?

  • http://link Merlin11

    Many, probably most, of these are chemical engineers or technicians rather than chemists per se. ,

blog comments powered by Disqus