Reading XML Files on the iPhone

November 30, 2008. Filed under objc 8 iphone 5

As I started working on my second will-go-to-market iPhone game, one of the most important improvements I made was moving configuration and level details to XML files from the very beginning. One of the differences between a great game and a mediocre game is flexibility, and storing details within XML files gives the gift of manifold flexibility (best of all, you can design a level or content format in XML, and then you can have non-programmers design content, and it's very easy to add content later on).

Fortunately, loading XML files on the iPhone is quite easy, once you pick up a couple of tricks.

The first step is to create a plist file:

  1. Go to File and then select New File....

  2. Scroll to the bottom of the list of templates, and select Other.

  3. From the templates, select Property List.

  4. Name the properly list settings.plist, and save it in your project.

  5. Add whatever data you're interested in. For this example let's say that you leave Root as a dictionary, and give it three keys:

    1. An array with the key levels.
    2. A string with the key title.
    3. A number with the key version.

Now wherever you want to load the code, you just need to write a few simple lines that look like this:

NSString * fileName = @"settings.plist";
NSString * path = [[NSBundle mainBundle] bundlePath];
NSString * fullPath = [path stringByAppendingPathComponent:fileName];
NSDictionary * root = [[NSDictionary alloc] initWithContentsOfFile:fullPath];

NSArray * levels = [root objectForKey:@"levels"];
NSString * title = [root objectForKey:@"title"];
int version - [[root objectForKey:@"version"] intValue];

[root release];

One gotcha to watch out for: even if you place all your XML files in a directory in your project folder named xml, that doesn't mean the file will be in a directory named xml once you build you application.