开发者

How to share preferences via NSUserDefaults for command line tools?

I want a half dozen command line tools (used for testing) to share a bundle ID so they can sh开发者_JAVA百科are a NSUserDefaults and Library/Caches subfolder. I could get around the Library/Caches subfolder by using a hard-coded string, but how can I set the file that NSUserDefaults saves to?

In a bundled application, it's set by the bundle ID, in Info.plist. But how can I set the bundle ID for a set of command line tools, which don't have an Info.plist?


Create an NSUserDefaults instance with +alloc & -init, instead of using +standardUserDefaults. A user defaults instance that's created this way won't be created with a defaults domain corresponding to the main bundle ID, so you need to use the -addSuiteNamed: method to manually add a defaults domain to it.

(Update) Sorry, my bad! Suites are volatile, not persistent - useful for tools that need to read a shared set of defaults, not so much for an application that wants to set a default value. For the latter, have a look at -setPersistentDomain:forName:. The keys in the domain dictionary define what keys belong to the named defaults domain, and the values supply their default values.

Here's a short example, that should create ~/Library/Defaults/com.shermpendley.DefaultsTest.plist, and store the listed key/value pair in it:

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    NSUserDefaults *defaults = [[NSUserDefaults alloc] init];
    [defaults setPersistentDomain:[NSDictionary dictionaryWithObject:@"Hello" forKey:@"World"] forName:@"com.shermpendley.DefaultsTest"];
    [defaults synchronize];
    [defaults release];

    [pool drain];
    return 0;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜