Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 663
user21293 Avatar asked Nov 26 '08 18:11

user21293


People also ask

How do I load files onto my iPhone?

Copy files from your computer to your iOS or iPadOS appDrag and drop files from a folder or window onto the Documents list to copy them to your device. You can also click Add in the Documents list in iTunes, find the file or files you want to copy from your computer, and then click Add.

How do I view iPhone files on my PC?

How to do it? Step 1: Install iTunes on your Windows or Mac PC and connect the iPhone to your computer. Step 2: Once iTunes start showing the iPhone in devices, you can click on it in the left sidebar and view the files. Step 3: You can open files and folders, change them, delete, or copy them to your PC with iTunes.

How do I add core data to an existing project?

Add a Core Data Model to an Existing ProjectChoose File > New > File and select the iOS platform tab. Scroll down to the Core Data section, select Data Model, and click Next. Name your model file, select its group and targets, and click Create.

Why are my files not opening on iPhone?

On the Settings screen, tap Cellular Data, scroll down, and then check that the switch next to Files is set to On. If you found it disabled, just turn it back on and you've fixed the problem already. If you didn't find anything unusual, then it's time to sign out and back into iCloud.


2 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];
like image 133
Ben Gottlieb Avatar answered Oct 05 '22 17:10

Ben Gottlieb


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"]];
like image 36
Chris Jefferson Avatar answered Oct 05 '22 19:10

Chris Jefferson