Loading data files in iPhone project

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!


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];

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"]];

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.

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

Need Your Help

SSCE - Multiple-Step OLE DB operation generated errors

vb.net sql-server-ce oledb

I'm using a SQL Server Compact database (3.5). I have run through every article on this site (and others) I could find about this issue, but can't seem to find the problem. I am using Visual Studio

"Pivoting" a Table in SQL (i.e. Cross tabulation / crosstabulation)

sql database oracle pivot

I'm working on trying to generate a report from a couple of database tables. The simplified version looks like this