kevingessner.com





Binding a Version Number in Cocoa

In the 1.3 release of FunctionFlip, I added an About box that shows the current version number. In the spirit of DRY, I didn’t want to hardcode the version number, as I’m likely to forget to change it in a future release. Since the information already exists in the bundle’s Info.plist file, I should treat that as the authoritative source. How could I get that information into my UI? Cocoa Bindings to the rescue!

The final result

The final result

Cocoa’s Display Bindings

First, I added an NSTextField to the About window in the project’s NIB. Thanks to the wonder that is Cocoa-plus-Interface-Builder, I can edit all of the field’s bindings directly from the IB Inspector. The binding of interest is “Display Pattern Value1”, in the “Value With Pattern” category. As explained in Apple’s docs this binding creates complex text from one or more bound values.

The bindings inspector

The bindings inspector

In my situation, I want to display the text “You’re using FunctionFlip x.y”, with x.y replaced with the version number. The binding uses a special form for the text you want replaced: %{value1}@ (or value2, etc.). So I set the Display Pattern value to “You’re using FunctionFlip %{value1}@”. Next, I bind the value to the text I want to appear; in this case, the bundleVersionNumber key of the window’s controller.

Providing the Version Number

Of course, the window controller doesn’t (yet) provide bundleVersionNumber. Since this is a read-only key, all I have to do is provide - (NSString *)bundleVersionNumber (line breaks marked \):

- (NSString *)bundleVersionNumber {
    return [[[NSBundle bundleWithIdentifier:\
        FF_PREFPANE_BUNDLE_IDENTIFIER] infoDictionary]\
        valueForKey:@"CFBundleVersion"];
} 

NSBundle’s infoDictionary method provides the contents of Info.plist as an NSDictionary. Then it’s just a matter of extracting the CFBundleVersion key, which holds the version number.

So that’s all there is to it—-the tight integration within the Cocoa API not only make the version number from Info.plist available in my code, but I can drop it into my UI with little code.

-- Kevin Gessner
October 13, 2008

This is part of Nihilartikel, my collected writings.
Back to the home page