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!

Answers


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

Need Your Help

Limit dropzone.js file upload

file-upload limit dropzone.js

I'm trying to limit the file uploads to allow uploading only 1 file. I'm pretty sure this has something to do with altering the selectedfiles callback, but haven't gotten it to work yet. Has anyone

Need the best way to iterate a file returning batches of lines as XML

scala iterator list-comprehension for-comprehension

I'm looking for the best way to process a file in which, based on the contents, i combine certain lines into XML and return the XML.