Load and Parse a File on the iPhone

Right now, I am hard at work on my next game. It is a puzzle style game, and I am using a variety of different tricks to pull it together. One of which is using my .NET skills to generate the actual puzzles on the Windows platform, then transfer them and use them on the Mac. I had to do some computations that I knew how to do easily on the PC, so I decided to use those skills (read: take a shortcut).

Anyway, this means that I had to be able to read in the file once I got it over to XCode. Luckily, like most things, there are an impressive amount of examples to do the load....assuming you don't need to parse the results and pass them into a custom object.

The format of my file is pretty simple: I am using an identifier for a node which is a string, then I am using 3 floating point values for the x-, y-, and z-coordinates of a point in 3-dimensional space. So I need to be able to read in the rows from the file, and parse out the results that I can use to create these custom nodes.

It was pretty tedious getting there, because the main method to parse out delimited strings, componentsSeparatedByString, returns types that you might not expect. Coming from a non-C background, I was slowed down by having to convert each node to something to be able to use it. I am a .NET guy...I expect some implicit conversion!!

Hopefully this bit of code helps you. This will load in all the lines in your string, parse out the values, then create a custom object for each one. Some of the supporting code is left out, so you can see the meat of the example; I also converted this to loading ints instead of floats because it made the code a little simpler. Enjoy!


NSString *filePath = [[NSBundle mainBundle] pathForResource:@"nodeOutputFile" ofType:@"txt"];
NSString *fileContents = [NSString stringWithContentsOfFile:filePath encoding:NSASCIIStringEncoding error:NULL];
if (fileContents) {

NSArray *lines = [fileContents componentsSeparatedByString:@"\n"];
for (int i = 0; i < [lines count]; i++) {

JTNode *newNode = [JTNode alloc];

NSArray *tokens = [[lines objectAtIndex:i] componentsSeparatedByString:@","];

NSString *identifier = [tokens objectAtIndex:0];

NSNumber *x = [NSNumber numberWithInt:[[tokens objectAtIndex:1] integerValue]];
NSNumber *y = [NSNumber numberWithInt:[[tokens objectAtIndex:2] integerValue]];
NSNumber *z = [NSNumber numberWithInt:[[tokens objectAtIndex:3] integerValue]];

[newNode createWithX:[x integerValue]
Y:[y integerValue]
Z:[z integerValue]
Identifier:identifier];


// do something here with newNode

}

}



Good luck to you!
John Tabernik

0 comments:

Post a Comment