How to retrieve values from settings.bundle in objective c?

北慕城南 提交于 2019-12-17 17:57:26

问题


I have created a project that set and retrieve values from settings.bundle. I have also set some defaults values in settings.bundle file. Now the problem is when I retrieve values as

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
loginName.text = [defaults objectForKey:@"login_name"];

for the first time it shows null, but the values get set in iPhone application settings. If I change the values or set it manually, then values are retrieved properly.

Help me out


回答1:


Although you define the defaults settings, they are not really stored as a value. They are stored as default. If you try to read it, the value is null. Default setting is another property as value is. But it doesnt mean that will write the default value as a default.

What I do is, first, check if some setting,(that I'm sure that should have a value) has anything stored on it. If it doesn't have anything then I write all the defaults.

Here is an example.

on AppDelegate.m I check if email_notificaciones_preference has a value, if not, I write ALL default settings to each setting.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    NSUserDefaults * standardUserDefaults = [NSUserDefaults standardUserDefaults];
    NSString * email_notificaciones_preference = [standardUserDefaults objectForKey:@"email_notificaciones_preference"];
    if (!email_notificaciones_preference) {
        [self registerDefaultsFromSettingsBundle];
    }

}

This function is what I use to write defaults to each element.

#pragma NSUserDefaults
- (void)registerDefaultsFromSettingsBundle {
    // this function writes default settings as settings
    NSString *settingsBundle = [[NSBundle mainBundle] pathForResource:@"Settings" ofType:@"bundle"];
    if(!settingsBundle) {
        NSLog(@"Could not find Settings.bundle");
        return;
    }

    NSDictionary *settings = [NSDictionary dictionaryWithContentsOfFile:[settingsBundle stringByAppendingPathComponent:@"Root.plist"]];
    NSArray *preferences = [settings objectForKey:@"PreferenceSpecifiers"];

    NSMutableDictionary *defaultsToRegister = [[NSMutableDictionary alloc] initWithCapacity:[preferences count]];
    for(NSDictionary *prefSpecification in preferences) {
        NSString *key = [prefSpecification objectForKey:@"Key"];
        if(key) {
            [defaultsToRegister setObject:[prefSpecification objectForKey:@"DefaultValue"] forKey:key];
            NSLog(@"writing as default %@ to the key %@",[prefSpecification objectForKey:@"DefaultValue"],key);
        }
    }

    [[NSUserDefaults standardUserDefaults] registerDefaults:defaultsToRegister];

}

Hope that helps.




回答2:


If anyone needs it - I translated the answer from MIQUEL to Swift (as good as I could as I'm still learning) :

var standardUserDefaults = NSUserDefaults.standardUserDefaults()
var us: AnyObject? = standardUserDefaults.objectForKey("your_preference")
if us==nil {
    self.registerDefaultsFromSettingsBundle();
}

And the func registerDefaultsFromSettingsBundle:

func registerDefaultsFromSettingsBundle() {
    // this function writes default settings as settings
    var settingsBundle = NSBundle.mainBundle().pathForResource("Settings", ofType: "bundle")
    if settingsBundle == nil {
        NSLog("Could not find Settings.bundle");
        return
    }
    var settings = NSDictionary(contentsOfFile:settingsBundle!.stringByAppendingPathComponent("Root.plist"))!
    var preferences: [NSDictionary] = settings.objectForKey("PreferenceSpecifiers") as [NSDictionary];
    var defaultsToRegister = NSMutableDictionary(capacity:(preferences.count));

    for prefSpecification:NSDictionary in preferences {
        var key: NSCopying? = prefSpecification.objectForKey("Key") as NSCopying?
        if key != nil {
            defaultsToRegister.setObject(prefSpecification.objectForKey("DefaultValue")!, forKey: key!)
        }
    }
    NSUserDefaults.standardUserDefaults().registerDefaults(defaultsToRegister);  
}



回答3:


Updated version for swift 2.1:

 func registerDefaultsFromSettingsBundle() {
    let userDefaults = NSUserDefaults.standardUserDefaults()

    if let settingsURL = NSBundle.mainBundle().URLForResource("Root", withExtension: "plist", subdirectory: "Settings.bundle"),
           settings = NSDictionary(contentsOfURL: settingsURL),
           preferences = settings["PreferenceSpecifiers"] as? [NSDictionary] {

        var defaultsToRegister = [String: AnyObject]()
        for prefSpecification in preferences {
            if let key = prefSpecification["Key"] as? String,
                   value = prefSpecification["DefaultValue"] {

                defaultsToRegister[key] = value
                NSLog("registerDefaultsFromSettingsBundle: (\(key), \(value)) \(value.dynamicType)")
            }
        }

        userDefaults.registerDefaults(defaultsToRegister);
    } else {
        NSLog("registerDefaultsFromSettingsBundle: Could not find Settings.bundle");
    }
}



回答4:


Updated for Swift 3:

func registerDefaultsFromSettingsBundle() {

    let userDefaults = UserDefaults.standard

    if let settingsURL = Bundle.main.url(forResource: "Root", withExtension: "plist", subdirectory: "Settings.bundle"),
        let settings = NSDictionary(contentsOf: settingsURL),
        let preferences = settings["PreferenceSpecifiers"] as? [NSDictionary] {

        var defaultsToRegister = [String: AnyObject]()
        for prefSpecification in preferences {
            if let key = prefSpecification["Key"] as? String,
                let value = prefSpecification["DefaultValue"] {

                defaultsToRegister[key] = value as AnyObject
                debugPrint("registerDefaultsFromSettingsBundle: (\(key), \(value)) \(type(of: value))")
            }
        }

        userDefaults.register(defaults: defaultsToRegister)

    } else {
        debugPrint("registerDefaultsFromSettingsBundle: Could not find Settings.bundle")
    }
}



回答5:


try this

To register Default Values of Setting bundles

NSDictionary *appDefaults = [NSDictionary dictionaryWithObject:defaultValue forKey:@"key"];
 [[NSUserDefaults standardUserDefaults] registerDefaults:appDefaults];

Before retrieving setting bundles values synchronize data

[[NSUserDefaults standardUserDefaults] synchronize]


来源:https://stackoverflow.com/questions/6291477/how-to-retrieve-values-from-settings-bundle-in-objective-c

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