简体   繁体   中英

iphone : Settings.bundle returns null value

I was using xCode 3.2 and then moved to xCode 4.2 and getting some values from Settings.bundle ... it was working fine.

Mean while I need to edit some values in Settings.bundle but The Root.plist file was not showing so I follow the below procedure but did not make any change in file.

1) Click on the Settings.Bundle file, go over to the utilities window,
and look in the File Inspector.
2) Using the drop-down, change the file type to 'Application Bundle'

After that I could see Root.plist but now could not get its values in application. Actually getting Null instead of value.

Below is code and image of Settings.bundle

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
host = [defaults stringForKey:@"meter_preference"];
if(host == nil)
{
    host = @"10.20.20.1";
    DDLogError(@"Meter host is nil from NSUserDefaults, defaulting to %@", host);
}

在此处输入图片说明

I got the solution, just call the below code in applicationDidFinishLaunchingWithOptions to initialize User defaults. and it works

Replace somePropertyYouExpect in first line with property you stored in User Defaults.

if (![[NSUserDefaults standardUserDefaults] objectForKey:@"somePropertyYouExpect"])  {

    NSString  *mainBundlePath = [[NSBundle mainBundle] bundlePath];
    NSString  *settingsPropertyListPath = [mainBundlePath
                                           stringByAppendingPathComponent:@"Settings.bundle/Root.plist"];

    NSDictionary *settingsPropertyList = [NSDictionary 
                                          dictionaryWithContentsOfFile:settingsPropertyListPath];

    NSMutableArray      *preferenceArray = [settingsPropertyList objectForKey:@"PreferenceSpecifiers"];
    NSMutableDictionary *registerableDictionary = [NSMutableDictionary dictionary];

    for (int i = 0; i < [preferenceArray count]; i++)  { 
        NSString  *key = [[preferenceArray objectAtIndex:i] objectForKey:@"Key"];

        if (key)  {
            id  value = [[preferenceArray objectAtIndex:i] objectForKey:@"DefaultValue"];
            [registerableDictionary setObject:value forKey:key];
        }
    }

    [[NSUserDefaults standardUserDefaults] registerDefaults:registerableDictionary]; 
    [[NSUserDefaults standardUserDefaults] synchronize]; 
} 

From your code , try this thinks..

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    host = [defaults stringForKey:@"meter_preference"];
    if(!host == nil)
    {
        host = @"10.20.20.1";
        DDLogError(@"Meter host is nil from NSUserDefaults, defaulting to %@", host);
    }

OR

Review this link may be helped you...

iPhone - reading Setting.bundle returns wrong values

NSUserDefaults Settings Bundle Plist

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM