iOS 8.2 [NSUserDefaults standardUserDefaults] retu

2019-07-21 17:47发布

I am encountering a strange issue in iOS 8.2 where [NSUserDefaults standardUserDefaults] is returning nil on iPhone. This same logic untouched has worked on all previous releases of iOS. I have a universal app which has two different settings.plist one for iPad and the other for iPhone list as follows;

Settings.bundle-
    -Root.plist
    -Root~iphone.plist

When installed on devices the correct settings pane displays and the user can input the appropriate values for the given fields. Though in my app at runtime [NSUserDefaults standardUserDefalts] returns a nil object.

What might I be doing wrong? Has Apple changed what is expected in 8.2?

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

userDefaults is always nil no matter what preferences are set in system settings.

1条回答
2楼-- · 2019-07-21 18:17

Did you set the dictionary to use as "Settings.bundle/Root.plist"?

// Register the preference defaults from file "Settings.bundle/Root.plist"
NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfFile:
                            [[NSBundle mainBundle] pathForResource:@"Settings.bundle/Root"
                                                            ofType:@"plist"]];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];

Thereafter [NSUserDefaults standardUserDefaults] no longer is nil.

In my case, the dictionary used by [NSUserDefaults standardUserDefaults] looks like this in the debugger:

    {
        PreferenceSpecifiers =     (
                    {
                DefaultValue = 1;
                Key = sortByDistance;
                Title = "Sortiere nach Entfernung";
                Type = PSToggleSwitchSpecifier;
            }
        );
        StringsTable = Root;
    }

To access the preferences I've written a tiny method:

- (id) preferenceValueForKey: (NSString *)key {
    NSArray *preferences = [[NSUserDefaults standardUserDefaults] arrayForKey:@"PreferenceSpecifiers"];
    NSUInteger index = [preferences indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
        return [[obj valueForKey:@"Key"] isEqualToString:key];
    }];
    return [preferences[index] valueForKey:@"DefaultValue"];
}
查看更多
登录 后发表回答