views:

2020

answers:

4

How does one read a data file in an iPhone project? For example, lets say I have a static file called "level.dat" that is structured as follows: obstacles: 10 time: 100 obstacle1: 10,20 ...

I would like to read the contents of the file into a NSString then do the parsing. How do I read the contents of a file into a string? Also, where in the project should the "level.dat" file reside? Should it be under "Resources" or just in the main directory?

Thanks in advance!

+8  A: 

See this answer: How to fopen() on the iPhone? which shows how to get access to resources in your bundle. Once you have the path, just use [NSString stringWithContentsOfFile:encoding:error:].

NSString   *path = [[NSBundle mainBundle] pathForResource: @"level" ofType: @"dat"]
NSError    *error = nil;
NSString   *data = [NSString stringWithContentsOfFile: path 
                                             encoding: NSUTF8StringEncoding 
                                                error: &error];
Ben Gottlieb
A: 

If you need help parsing the data string, there's a helpful article on Cocoa For Scientist

Dan
+2  A: 

While this isn't what you asked for, consider turning your files into plists. You will have to reformat them into XML, but then you can load them straight into a NSDictionary with:

dict = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"levels" ofType:@"plist"]];
Chris Jefferson
Note that you can do the same thing with arrays, it's very likely his data may be more suited to a top level of arrays rather than a dictionary.
Kendall Helmstetter Gelner
A: 

Have you considered putting the data in an SQLite database instead of a flat file? I find that the API is very easy to use on the iPhone.

It is how I do all of my data storage on the phone now.

Lee