views:

980

answers:

3

In my app, I have a simple ASCII file which stores some config info and other small info which it uses and changes. I want to copy that file to the iPhone with the app.

1) Please tell me where I should put this file (config.txt) in xcode. Should I put it under Resources ?

2) How will I access it in the iPhone ? Can I just use

str = [NSString stringWithContentsOfFile:@"config.txt"]

or do I have to use a more complete path; if yes, what is that ?

+6  A: 

You should use NSUserDefaults to store user settings, if the application can change them. The documentation is here.

The settings are stored as a plist file, so you can store NSDictionary instances, NSArray instances, etc.

If you want to pre-populate your NSUserDefaults with some settings, you can do so with some code like this one:

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

You need to put a defaults.plist file on your Resources folder with the default settings, and use the code above. I run that code from the AppDelegate's +(void)initialize method, but you can choose another place to call it.

pgb
I want to store some default options to be picked from by the user. He can add more options to his taste as he uses the app. e.g. for a bird watching app, the initial options could be "dove", "sparrow" etc. The user can add others like "eagle". The list might become large (100 entries say). Is NSUserDefaults still a good option ?
euphoria83
I'd recommend you try loading big plist files on the device (not the simulator) to test the performance.If you need more performance, you may want to check SQLite and store the information on a DB instead.
pgb
How do I have a file with pre-existing key-value pairs and then access it using NSUserDefaults ?
euphoria83
I edited my answer with some sample code for that. Hope it helps.
pgb
Thanx. It helped.
euphoria83
+1  A: 

You can put it in Resources, yes. To get the file, then, you can simply use:

[[NSBundle mainBundle] pathForResource:@"config" ofType:@"txt" inDirectory:@""]]

May I suggest NSUserDefaults for your settings, however? It will save you plenty of trouble in reading and writing them.

Sören Kuklau
A: 

If nsuserdefaults doesn't meet your needs, you could store the config information in a file in the Documents directory. If the file doesn't exist on startup, then read the version you have in Resources.

Mark Bessey