More of a programming nerd than is strictly healthy. See also {nevyn.nu, thirdcog.eu, twitter}

Projects

Overooped

Low Verbosity KVO

DRY Cocoa: SPLowVerbosity

I love Objective-C. It’s a very explicit language: there is no magic in the language. If you want such magic as distributed objects, model classes generated at runtime, generic change notification, or heck, even referenced counted memory management, you can implement it yourself in a library. It’s also by convention a very verbose language. If the method name doesn’t say exactly what the method does, the author is doing it wrong.

However, there are some things we type over and over again every day, whose verbosity does not make the code more readable but only serves to pad the code file with useless characters. These are in particular array and dictionary literals, and formatted strings.

ObjC wizard Jens Alfke wrote MYUtilities quite a while ago, and in particular CollectionUtils. This header defines a few very handy macros such as $array(...), $dict(...) and $sprintf(...). $array is simply a shorthand for [NSArray arrayWithObjects:..., nil] (note the extra nil, freeing you from typing that yourself every time, and also avoiding a possible crash). $dict is NSDictionary’s constructor, with the arguments in the right order (key, value, key, value, …). $sprintf is [NSString stringWithFormat:]. It may seem trivial, but this simple header has saved me tons and tons of typing, and surely from some silly bugs as well.

For more C++ friendliness, and to not have to depend on the rest of MYUtilities, I wrote my own, called SPLowVerbosity, with mostly the same things. The details are not interesting, so I won’t list the code; click through if you are curious.

This is a hack, and while it is very convenient, it is not pretty. Objective-C needs in-language literals for arrays, sets, dictionaries and number objects.

I do believe that such literals are now inevitable, though. With ARC, what I wrote in the first paragraph is no longer entirely true. Dealloc now magically calls super. Memory management is implicit and part of the language, not explicit and manual. The sanctity of Objective-C’s simplicity has been violated, parts of Cocoa has been moved into the language. Moving more parts of Cocoa into the language (e g exposing APIs saying ‘this is the class that should be instantiated when I use a dictionary literal’) no longer has a high religious price, and I bet we’ll see it at next year’s WWDC.

Object-Oriented KVO: SPKVONotificationCenter

During the past few years, my nose has started to really pick up on a code smell I didn’t feel before: unencapsulated concepts. What I mean by that is an API concept or contract that is only visible in comments and documentation, thus only implicit by knowledge of that documentation when you read code using the API, instead of exposing the concept as a construct the language can help you manage.

Examples:

Instead of the above concepts being implicit and only visible in documentation, several of them can be represented as objects and closures, thus making it impossible to do wrong.

The realization is not new, of course. It’s quite common to use RAII patterns in C++ to encapsulate concepts in code, giving them an explicit start point and a managed (and deterministic) end point.

But this is Objective-C, not C++, so we don’t have RAII. We do have objects, however, and if we use them to actually represent our objects, we can clean up so much code.

SPKVOObservation is an object that represents a KVO subscription. When this object is created, you know you have your subscription. When this object disappears, you know the subscription is gone. By managing instances of this class like I would any other instance variable, I know I’m following KVO’s subscribe/unsubscribe contract. (With ARC, I don’t even have to manage the ivar).

SPKVONotificationCenter also has dispatch to a given selector instead of the catch-all -[NSObject observeValueForKeyPath:ofObject:change:context:].

(As for solutions for the rest of the examples: a closure can be used for the mutex case if in the current scope, otherwise you might want RAII (which is possible with GNU extensions even in C). For the table view, I’d prefer bindings, but doing to-many KVO and bindings can be really hard, so I doubt we’ll be seeing it on iOS in the near future.)

DRY KVO: SPDepends

I love KVO. Basically every library I’ve ever used has their own implementation of notifications on attribute changes. Such an implementation is of course not difficult, but because there is no generic system for it in other languages/platforms, you can’t build a framework for working with change notifications generically. Recognizing that this is a generic concept, and then as good as building it into the language is genius, and has given us wonders such as bindings.

Outside of their use in bindings where you have tool help, KVO’s API is pretty bad, and working with it is almost painfully verbose (made worse by the single callback point, spreading your code out all over the file). What I really wanted to do was to unify the two above sections for a very simple, non-verbose and object oriented approach to KVO. The result is SPDepends. Magic is taken to the next level; we are approaching dark arts. Whether what I’m about to present is actually a good idea or not, I leave as an exercise for the reader. First, the header:

tl;dr: SPDepends lets you give it a list of {object, key path(s)} pairs that one of your properties depend on. When the value of any of the given key paths changes, a given closure is called, letting you recalculate the dependent property (or whatever you want to do). It’s about as far as you can go with KVO without actually building bindings.

There is one additional piece of magic related to memory management (this was before ARC). By providing an owner and associationName, the dependency is assigned as an associatedObject, so that it will automatically be cleaned up when the owner object dies. Defining a dependency again with the same name will also throw away the old dependency. If this is not desired, you can just not provide the association name, and instead manage the returned SPKVOObservation object on your own.

Example:

Output:

Note how short the $depends macro makes all your KVO work. The macro also defines a block-safe self variable selff that won’t create a reference cycle.

The equivalent classical KVO code would be many lines longer. However, this macro takes several steps away from how Cocoa code is normally written. Is the syntax too obscure? Is the code still readable for normal human beings?

Media keys hook in Mac OS X

There is no nice (or is it even official?) way of detecting and handling the media keys on the user’s keyboard. One can intercept events with type NSSystemDefined and subtype 8 in -[NSApplication sendEvents:], but this has major problem: any other applications that listen to the media keys will receive these events too. This means for example that if only Spotify is running and you want to pause your music, iTunes will start when you press play/pause. If you have VLC running in the background, it will also start playing.

Apple has solved this problem internally by having their media key using applications cooperate and resign media key controls to the application that was in the foreground most recently. However, there is no way for third party applications to join this cooperation.

I have implemented a workaround that does this using a CGEventTap in the Cocoa class SPMediaKeyTap. The advantage of using an event tap instead of just intercepting the events in -[NSApplication sendEvent:] is that you have the power to throw the event away. This way, we can decide to “own” the media keys and be the only app that listens to them.

This class is smart enough to resign the media key event tap whenever another application that we know will want to use the media keys becomes active, and keeps track of which media key using app was recently started.

If everyone uses this class, and everyone add each other’s bundle ID to that list of whitelisted bundle ID’s, we’ll get nice behavior from all apps. An even better solution would be if Apple provided a way of acquiring the media keys.

Re: Firefox 3 vs. Safari 3

I agree with everything that Gruber writes about in his latest article. A friend of mine went majorly goddamned-mac-zealot on me and his article (had to explain not once but *twice* that Gruber wasn’t saying “FF should be exactly as Safari” but “Safari beats the Mac port of FF on a number of points” :P) All is well and good though, as he found a fix for the most annoying UI element of FF3 for me: single-click-selects-entire-URL. I almost screamed from frustration from just trying to edit the URL a few days ago. Here’s how to fix it, though:

  1. Go to about:config (type it in the location bar and type enter)
  2. Filter on “clickSelects”
  3. Double-click on the row that says “browser.urlbar.clickSelectsAll” to set it to false.

Now when you single-click in a Firefox location bar, it’ll place the caret in it; double click will select word; and triple-click will select the whole line, just like in a Mac app.

Addendum: Okay, so Voxar tried to convince me that Safari’s location bar was idiotic and illogical (of course only from reading Gruber’s article and not trying it out, even though he has a Mac on his desk :P), and challenged me: if Safari always highlights the first autocomplete entry when you type an url, wouldn’t it be VERY cumbersome to enter e g “http://daringfireball.net/2008/” when the only URL in your history is “http://daringfireball.net/2008/04/firefox_3_safari_3”? The answer is of course, no :) In Safari, you type “da[right-arrow]2008[backspace][enter]” and you’re done with it. The same scenario in Firefox would require you to type the entire URL in by hand, since the autocomplete would be completely useless (even the AwesomeBar would be stumped!). Now I remember why I love Safari :) (Watch It In Full Motion.)