Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
952 views
in Technique[技术] by (71.8m points)

xcode - Register default settings from the Settings.bundle plist file?

I'm adding a Settings.bundle file to my iOS application. It's very minimal with one or two settings. The plist file in the Settings.bundle specifies the defaults, to the Settings application. I've read that to make my iOS application aware of these defaults, I have to also code them into my application. This seems like repeating myself and leaving an opening for defaults to easily get out of sync as I modify the program.

I know I can register the defaults using the contents of plist file, like so:

[[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Defaults" ofType:@"plist"]]];

That also seems like repeating myself, though. Would it be possible to use the plist file from the Settings.bundle as the source of these defaults, so that I only specify defaults in 1 location?

I trued adjusting that load to look something like this:

[[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Settings.bundle/Root" ofType:@"plist"]]];

That did not work, though. Does anybody know if this is possible, and how to load that plist file?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Wanted to add this as a comment to Andy's answer, but Stack Overflow didn't let me (too long for a comment).
If you're using ObjC here's your version:

-(void)registerDefaults
{
    NSString* pathString = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"Settings.bundle"];
    NSString* rootPath = [pathString stringByAppendingPathComponent:@"Root.plist"];
    NSDictionary* settingsDict = [NSDictionary dictionaryWithContentsOfFile:rootPath];
    NSArray* prefSpecifiers = settingsDict[@"PreferenceSpecifiers"] ;

    NSMutableDictionary* defaults = [NSMutableDictionary dictionary];

    for (NSDictionary* item in prefSpecifiers) {
        NSString* theKey = item[@"Key"];
        NSObject* defaultValue = item[@"DefaultValue"];

        if (defaultValue && theKey) {
            defaults[theKey] = defaultValue;
        }

    }

    if (defaults.count > 0) {
        [[NSUserDefaults standardUserDefaults] registerDefaults:defaults];
    }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...