Get Users Home Directory – Part 2

In the previous tip on working with plists, I showed an example of how to create a path to a file to be stored in the /Documents folder.

In this tip I want to show an example that arrives at the same end result, however, I’ll use methods which will eliminate the hardcoding of paths as shown in the first example.

To quickly recap, the intention was to create a file named User.plist and store that file in the user’s documents folder. In the previous post I specified the full file path I was after (/Documents/User.plist) and then appended that path to the user’s home directory.

Here’s another approach:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
    NSUserDomainMask, YES);
 
if ([paths count] > 0)
{
  NSString  *plistPath = [[paths objectAtIndex:0] 
                                 stringByAppendingPathComponent:@"User.plist"];
 
  // Check for existence of the file
  if ([[NSFileManager defaultManager] fileExistsAtPath:plistPath])
    ... 
  else
    ...
}

With this approach I request the path to the documents directory through a call to NSSearchPathForDirectoriesInDomains by specifying NSDocumentDirectory as the search path. To build the fullpath I first retrieve the path to the documents directory ([paths objectAtIndex:0]) and append the filename that I am after through a call to stringByAppendingPathComponent. The later call will prepend a path separator and append the filename requested.

The end result, with no hardcoding: /Documents/User.plist