2

I know how to read/write to local files on iOS using file handles. I can dynamically create and read/write form them. What I'm trying to do right now is to include a file, about 200 lines long with the app bundle, which I hope to parse and extract configuration settings from. I really do not want to have to create an array of 200 numbers by hand.

How would I go about including a text file with the app, and making it accessible from my application?

Thank you!

Alex Stone
  • 46,408
  • 55
  • 231
  • 407

2 Answers2

3

You can include a file in the bundle by adding it to your Resources folder in Xcode and making sure that it is included in your target as well. To access a file in the bundle (e.g., a text file called info.txt), you can get the path using:

[[NSBundle mainBundle] pathForResource:@"info" ofType:@"txt"]

Then access it using the normal NSFileManager methods.

EDIT: With this said, you can't write anything into this file inside the bundle on iOS. Instead, you can copy the file from the bundle to a file system location (say, your app's Application Support folder) on first launch, then access it there elsewhere in your app.

Sean
  • 5,810
  • 2
  • 33
  • 41
3

Why don't you create a dictionary with Property List Editor and load it like

NSString *configurationPath = [[NSBundle mainBundle] pathForResource: @"configuration" ofType: @"plist"];
NSDictionary *configuration = [NSDictionary dictionaryWithContentsOfFile: configurationPath];

So you can access its settings with

[configuration objectForKey: @"someSetting"];

If you want to write, I recommend registering that dictionary with NSUserDefaults so you could write to a copy like

[[NSUserDefaults standardUserDefaults] setObject: someSetting forKey: @"someSetting"];
Jef
  • 2,134
  • 15
  • 17
  • NSDictionaries are something completely new to me. I was hoping to include a .CSV file with 200 lines x5 values each that I can parse easily using the same logic that I use to read/write my regular log files. It sounds like for the Dictionary path I'll have to do even more work than creating an array by hand – Alex Stone Nov 11 '11 at 15:28
  • @AlexStone: The advantage of NSDictionaries or PLists would be that you get the parsing for free. With a CSV, you need to write the parser yourself (you might need support for escaping characters and stuff). – DarkDust Nov 11 '11 at 15:32
  • @AlexStone: I second what Darkdust says. You're describing exactly what Apple invented NSDictionary and NSUserDefaults for. I bet it will even be faster than any CSV approach because NSDictionary and NSUserDefaults are optimized to the max. Note: if you don't know how to work around NSDictionaries I really recommend you to read some tutorials. – Jef Nov 11 '11 at 15:40