Cocoa equivalent of .NET's Environment.SpecialFolder for saving preferences/settings?

谁说我不能喝 提交于 2019-12-10 06:28:10

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/359590/cocoa-equivalent-of-nets-environment-specialfolder-for-saving-preferences-sett

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!