Cocoa Bindings are awesome, yet fraught with peril for the inexperienced

Apparently ivars that are bound to from a nib, via a controller object, don’t have an initial or default value unless I assign one either via code or via the UI element.

Almost all of my experience with the NeXT and Apple APIs pre-dates bindings and core data by nearly a decade, but I’ve had enough of the kool-aid to know the lines of code I never write are much less likely to have bugs than the lines I do write.

Lately I’ve been working on a couple of one-off apps for my personal use, and also to help my mom with gallery images for her website. In the process I’m learning that the practice of bindings is a bit more complicated than the theory of bindings.

For example, I’m working on a simple application that takes a directory full of images, scales each one to a particular square dimension, and pads the shorter side with a user-chosen color. In the NIB for this app, I have an NSTextField for the target dimension and an NSColorWell for the background color.

I’ve discovered that when I launch the app, those IB elements that are bound through an NSObjectController to ivars in MyDocument don’t have an initial default value! For example one of my ivars is *backgroundColor, and the color well is bound to it through the NSObjectController. If I try to read that value from another method in MyDocument without first setting it either via code, e.g. backgroundColor = [NSColor colorBlack], or via the NSColorWell UI element itself, the ivar will be nil! I spent half an hour this afternoon using GDB to track this backwards through my set of Core Image filters before I finally figured it out.

Anyone know how to fix this? I see Core Data has a willReadValueForKey: but I don’t know if it would do the trick.

This entry was posted in Uncategorized and tagged . Bookmark the permalink.

One Response to Cocoa Bindings are awesome, yet fraught with peril for the inexperienced

  1. frank says:

    Another way to work around the initial value problem is to bind the UI element to the user defaults instead of to an ivar. Then, where you previously refereced the variable, use a method that fetches it from the standard user defaults. I got this usage pattern from Thumb Borker, a thumbnail generation application that I probably would have started from if I’d found it a couple of weeks ago. I’m glad I did all that stuff myself because I learned a lot, but also glad for the examples of other and better ways of handling things I got from this app.

Comments are closed.