Saturday, October 9, 2010

How Could I Live Without Property Lists?

I've started to use property lists.  At first I avoided them since I thought they were daunting, but they are the easiest thing in the world to use!

What's the first thing we should do?  First, let's get the path to our property list from the main bundle:

NSBundle *mb = [NSBundle mainBundle];
NSString *dataPath = [mb pathForResource:@"MyPropertyListFile" ofType:@"plist"];



Second, for good measure, we should make sure that the object was found:

if (dataPath == nil)
NSLog(@"Unable to find MyPropertyListFile p.plist");


Ok, you'd want to do more than output a simple line of text.   Next, we want to open the file.  I recommend mapping the file to memory - so if the system gets low on resources it can the memory used by the contents of the property list file:

NSData *data = [NSData dataWithContentsOfMappedFile:dataPath];


Next; let's get the content found within our property list:

NSDictionary *Plist
= [NSPropertyListSerialization propertyListFromData:data
mutabilityOption:0
format:NULL
errorDescription:nil];

Ok.  That's it!  The contents of the property list file is within the dictionary.  To be honest, the method I'm using will be deprecated soon - but it works in iOS 3.x where the newer method only work in iOS 4.x.  Nonetheless, they both do something very similar.

Now, using a property list editor (either XCode or the one in the Utilities folder within the Applications folder) - edit your property lists as you please.  Dictionary types allow you to assign string keys to values (of varying type).  Arrays give you a list.  The others are scalar types.

What's great is that each maps to their underlying NSObject counterparts.  So a dictionary in a property list becomes an NSDictionary.

I'm aware that property lists can act as data sources and do much more complicated work.  However, they make for very nifty configuration files.  With less than a dozen lines of code you can open a property list and extract data from it.

With external configuration files so easy to set up; there is little excuse to hard code values that might change later on.

<minirant>
I used to write my own parsers to load configurations from external files.  Then I started to dump them in header files.  However, property lists are a much more elegant solution as they don't need a recompile.  Data can simply be queried from a dictionary root object...
</minirant>

No comments:

Post a Comment