Settings.bundle ... why can't my code access the values via [NSUserDefaults standardUserDefaults]?

StackOverflow https://stackoverflow.com/questions/15693671

문제

I don't understand the logic:

When I create a settings bundle the values are nil when accessed from code via

[[NSUserDefaults standardUserDefaults] stringForKey:@"mykey1"]

But as soon as I touch this key via the Settings.app this key is readable by my code.

Solutions I found require to read the file "Root.plist", build a dictionary from it, register the values and synchronize them.

I read the Apple docu multiple times - I still do not understand the idea and the standard pattern for delivering an app with a set of standard settings.

Any hints for my studies?

도움이 되었습니까?

해결책

The existence of a Settings.bundle does not have any effect on NSUserDefaults. It's not until a value is changed from its default that the value is reflected in NSUserDefaults.

The proper solution is to use NSUserDefaults registerDefaults:. In many cases, you load the dictionary of defaults with the contents of the Root.plist. You do not need to call synchronize for this. The defaults get registered every time your app runs. The values are not actually stored. When you ask for a value from NSUserDefaults, if no explicit value exists, then the registered defaults are looked at for a value.

You should register the defaults as soon as possible at app startup.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top