I'm adding a Settings.bundle file to my iOS application. It's very minimal with one or two settings. The plist file in the Settings.bundle specifies the defaults, to the Settings application. I've read that to make my iOS application aware of these defaults, I have to also code them into my application. This seems like repeating myself and leaving an opening for defaults to easily get out of sync as I modify the program.
I know I can register the defaults using the contents of plist file, like so:
[[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Defaults" ofType:@"plist"]]];
That also seems like repeating myself, though. Would it be possible to use the plist file from the Settings.bundle as the source of these defaults, so that I only specify defaults in 1 location?
I trued adjusting that load to look something like this:
[[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Settings.bundle/Root" ofType:@"plist"]]];
That did not work, though. Does anybody know if this is possible, and how to load that plist file?
That is not necessary, you can simply call the data in the plist by calling the key that it was assigned to in the plist, for example,
Yes, it is possible. Here's how you would do it in Swift:
That will load the DefaultValue from each PreferenceSpecifier with a Key. For example:
The
loadDefaults
function will load the default value of 15 into the user default for "frequency".I recommend you call the
loadDefaults
function your app delegate, from thedidFinishLaunchingWithOptions
handler, like this:Then later in your app, say in a
UITableViewController
, you can load the user default value like this:Based on Andy's answer above, adapted for Swift 4, and avoiding the use of force-unwrap/force-cast:
Wanted to add this as a comment to Andy's answer, but Stack Overflow didn't let me (too long for a comment).
If you're using ObjC here's your version: