NSUserDefaults Settings Bundle Plist

2020-04-30 02:51发布

I have an app that checks for a file upon load from the appDelegate's appDidFinishLoading method using a url value that I supposedly store in the NSUserDefaults Settings Root Plist:

NSString *pathStr = [[NSBundle mainBundle] bundlePath];
NSString *settingsBundlePath = [pathStr stringByAppendingPathComponent:@"Settings.bundle"];
NSString *finalPath = [settingsBundlePath stringByAppendingPathComponent:@"Root.plist"];
NSDictionary *settingsDict = [NSDictionary dictionaryWithContentsOfFile:finalPath];
NSArray *prefSpecifierArray = [settingsDict objectForKey:@"PreferenceSpecifiers"];

NSDictionary *prefItem;
for (prefItem in prefSpecifierArray){
    NSString *keyValueStr = [prefItem objectForKey:@"Key"];
    if ([keyValueStr isEqualToString:kFirstNameKey]){
        nsUserDefURL = [prefItem objectForKey:@"DefaultValue"];
    }
        if ([keyValueStr isEqualToString:kSecondNameKey]){
        NSLog(@"You are using local data:%@",[prefItem objectForKey:@"DefaultValue"]);
    }
}
NSLog(@" this is the url == %@", nsUserDefURL);

// since no default values have been set (i.e. no preferences file created), create it here     
NSDictionary *appDefaults = [NSDictionary dictionaryWithObjectsAndKeys:nsUserDefURL,kFirstNameKey,@"YES",kSecondNameKey,nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:appDefaults];
[[NSUserDefaults standardUserDefaults] synchronize];

with some statics:

NSString *kFirstNameKey = @"url";
NSString *kSecondNameKey = @"Web DataSource";

When I NSLog the nsUserDefURL, i still get the default value in the settings plist. I went into the settings for the app (didn't know i could do so in the simulator) and I modified the value in the url field, but i STILL get the test2.xml value that is the default placeholder value in the settings root plist.

Here is the plist:Root.Plist

Or is it that the settings bundle doesn't work on the Xcode simulator?

2条回答
太酷不给撩
2楼-- · 2020-04-30 03:06

Turns out I was missing this line:

nsUserDefURL = [[NSUserDefaults standardUserDefaults] stringForKey:kFirstNameKey];  

But this only reads the default value each launch. It won't save the user modified value in the app settings. Why is that value not being saved?

查看更多
欢心
3楼-- · 2020-04-30 03:21

You'll need to explicitly save it. For example, if strFirstName is the value that the user modified, then you would save it to the app settings by

 NSUserDefaults* ud = [NSUserDefaults standardUserDefaults];
 [ud setObject:strFirstName forKey:kFirstNameKey];
 [ud sychronize];
查看更多
登录 后发表回答