NSString+Templating Revisited

My NSString+Templating category continues to evolve, so here are a few notes for those who care:

  • First, and most importantly, the incredibly knowledgeable and always helpful Scott Anguish pointed me to nice solution for one of the problems I had mentioned in a previous post: the need to provide “pre-processing” of a field’s text before it is put into the template.

    Scott’s solution takes advantage of yet another key-value coding feature I hadn’t noticed: the valueForKeyPath: method. The difference between this and the more commonly used valueForKey: method is sort of difficult to explain, but basically, it allows you to chain keys together such that the value of one key becomes the object from which the value of another key is derived.

    The key path is represented using a dot notation. For example, suppose we have a “Car” object, and it has a field called “engine” (an object of type “Engine”), which in turn has a field called “type” (which is just an NSString). From a Car model object, the engine type would be accessible using the following code:

    [theCar valueForKeyPath: @"engine.type"];

    As Scott suggests, we can leverage this technique to provide the “pre-processing” I was previously looking for. The trick is to put whatever formatting methods we need into our NSString category. Then, from the template, we can take whatever string output we get from a field and run it through our formatter (which is now a method of NSString) like so:

    <$name.stringByEscapingQuotes/>

    I really like this solution because it actually enables the template designer to specify formatted or unformatted output simply by choosing whether or not to chain the formatter onto the end of the key.

    The posted code has been updated to use valueForKeyPath: instead of valueForKey:, and the category now also contains several sample formatting methods (including one to escape quotes).

  • Now that Panther is out, I’m posting an Xcode project containing both the category itself and a snazzy little app I whipped up to demonstrate its usage. Download it here:

    - TemplateTest.dmg (30k)

    For those not using Panther/Xcode, I’m also still distributing the code by itself:

    - NSString+Templating.dmg (9k)

  • My previous distributions were inadvertently marked as governed by the Creative Commons Attribution-NonCommercial License. This was a mistake—I have no problem with NSString+Templating being used in commercial applications. The new version has been switched to the plain old Attribution License.

Leave a Reply