testing
testing

Reputation: 20279

Store preferences in a file and import values to initialize variables

I want to store the content of some variables in a file. The user nor the application should change the value. It would be great if the user cannot read the content of this file. On startup the application reads the file and initialize some (global?) variables with the content.

The file should contain some values like server URL and so on. This could change, but I only want to manage a preference file rather than updating the source code. On an update for example only the preference file will get exchanged.

How can I manage that?

NSUserDefaults is not intended for such issues I think. Should I use a a plist or a normal txt file?

How would the access to the content of the file look like?

Cheers

Upvotes: 0

Views: 623

Answers (3)

testing
testing

Reputation: 20279

So the solution I'll use is that I load a plist file as default value for my NSUserDefaults:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Settings" ofType:@"plist"];
NSDictionary *settingsDict = [NSDictionary dictionaryWithContentsOfFile:filePath];
[[NSUserDefaults standardUserDefaults] registerDefaults:settingsDict];
NSUserDefaults *settings = [NSUserDefaults standardUserDefaults];

NSString *serverURL = [settings stringForKey:@"ServerURL"];
NSLog(@"%@", serverURL);

Taken from iPhone App : Where do I put a config file?

So I'll use both plists and NSUserDefaults. settings I'll define as global variable in the main.m. One problem remains:

How to differentiate between user defaults and system defaults?

Upvotes: 0

Brian
Brian

Reputation: 15706

Use a plist. You can load it with -[NSDictionary initWithContentsOfFile:] (you can save a dictionary to a plist just as easily with -[NSDictionary writeToFile:atomically:], though it doesn't sound like you need to do that).

Upvotes: 0

Toastor
Toastor

Reputation: 8990

Sounds to me like NSUserDefaults is exactly what you need. It will let you store URLs (as strings) and other basic types of variables.

Why do you think NSUserDefaults is not the right solution here?

Give it a try! It's easy to use and reliable.

Upvotes: 1

Related Questions