iOS 8.2 [NSUserDefaults standardUserDefaults] returning nil
Asked Answered
S

1

2

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.

Setiform answered 19/3, 2015 at 21:33 Comment(2)
Works fine with me, in iOS 8.2. Do you want to post a code snippet, to show what you're doing ?Republicanize
Hi mike thanks for your response. You must first remove your application and download new from app store. I initially thought the same as my app was working on my device 8.2 which my application binary was brought over from a previous install from 8.1. But once I removed my application on 8.2 and reinstalled from the appstore I was able to reproduce the issueSetiform
S
3

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"];
}
Subtorrid answered 3/4, 2015 at 12:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.