views:

551

answers:

2

How do I get the reference to a folder for storing per-user-per-application settings when writing an Objective-C Cocoa app in Xcode?

In .NET I would use the Environment.SpecialFolder enumeration:

Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);

What's the Cocoa equivalent?

+10  A: 

In Mac OSX application preferences are stored automatically through NSUserDefaults, which saves them to a .plist file ~/Library/Preferences/. You shouldn't need to do anything with this file, NSUserDefaults will handle everything for you.

If you have a data file in a non-document based application (such as AddressBook.app), you should store it in ~/Library/Application Support/Your App Name/. There's no built-in method to find or create this folder, you'll need to do it yourself. Here's an example from one of my own applications, if you look at some of the Xcode project templates, you'll see a similar method.

+ (NSString *)applicationSupportFolder;
{
    // Find this application's Application Support Folder, creating it if 
    // needed.

    NSString *appName, *supportPath = nil;
    NSArray *paths = NSSearchPathForDirectoriesInDomains( NSApplicationSupportDirectory, NSUserDomainMask, YES );

    if ( [paths count] > 0)
    {
     appName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleExecutable"];
        supportPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:appName];

        if ( ![[NSFileManager defaultManager] fileExistsAtPath:supportPath] )
      if ( ![[NSFileManager defaultManager] createDirectoryAtPath:supportPath attributes:nil] )
       supportPath = nil;
    }

    return supportPath;
}

Keep in mind that if your app is popular you'll probably get requests to be able to have multiple library files for different users sharing the same account. If you want to support this, the convention is to prompt for a path to use when the application is started holding down the alt/option key.

Marc Charbonneau
A: 

For most stuff, you should just use the NSUserDefaults API which takes care of persisting settings on disk for you.

Mike Abdullah