multipart-message nevyn bengtsson's blog

featured articles 🦄, about, archive, tags

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:

  • Mutex locking as two separate functions that must always be paired. This is an easy to make mistake, and can be very difficult to fix in complexly branching code. Static analyzation can find such errors, but is in my opinion the wrong approach.
  • UITableView’s beginUpdates/endUpdates must always be called in a pair, and all the updates you make in that pair must match the changes you are doing to the data source.
  • NSNotificationCenter requires you to register for a notification with a {sender, receiver, name} triplet, and reuse that triplet to destroy the subscription. In practice what you have here is an implicit object that you must manage using an awkward object triplet, rather than an actual object.
  • Key-Value Observing, with the same defect as with notifications, plus that callbacks are dispatched to the same instance method, forcing you to use the triplet plus a context pointer as the identifier again.

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?

no title


THIS. This is how to teach math. The contrast between the Wikipedia page and this application’s UI is striking.

File format plugin API for Spotify?

At Spotify, we have one and a half day of ‘hackday’ ('code whatever you want’, the '20% time’ concept from Google) every sprint. Since the past few months have been a bit hectic finishing up the new 0.5.0 release, we haven’t really had time for that in a while, and thus compensated by having a whole week of crazy hacking this week. I managed to finish two features in that time; one in the iOS client (of which I will only say: Loren Brichter is my hero!), and one in the desktop client: file format plugins.

Last year, one of my hackday projects was integrating blargg’s Game Music Emu into Spotify, thus letting you play NES, GameBoy, SNES, Genesis, PC Engine and other console’s music files in Spotify. Just a few days of work, and suddenly I had the best console music player app in the world, with playqueue, playlists and whatnot. However, GME is LGPL and we statically link our dependencies, so there was no way I could release it :(

Thus, I aimed to hit two birds with one stone: by adding a file format plugin API to Spotify, I could a) enable anyone to add support for their favorite file format in Spotify (flac, mikmod, sid, …) b) let me release the GME support as an open source plugin!

However, I’ve never designed a plugin API in C before, and if we’re going to release it and support it for quite a while, it should be well designed, easy to use, and cover all the basic needs. It’s versioned, so it should be simple to add new things to the API, but changing the existing ones might be tricky. So, my question is: do you have any feedback for me on this api?

When you hand a recursive mutex down from one routine to another, the callee cannot know the state of predicates in the caller. It has to assume there are some, because it cannot verify there aren’t; and if the caller had known that there were no broken predicates, it should have allowed concurrency by unlocking.

When you hand a recursive mutex down from one routine to another, the callee cannot know the state of predicates in the caller. It has to assume there are some, because it cannot verify there aren’t; and if the caller had known that there were no broken predicates, it should have allowed concurrency by unlocking.

So, late night hacking trying to fix a stupid bug in Spotify. Find out that all mutexes in the Spotify codebase are recursive. Googleathon about recursive locks. Find interesting stackoverflow answers and blog posts and stuff. Some say recursive locks are Evil, but their arguments aren’t super-solid. Find the guy who wrote recursive locks in pthreads. He has good arguments.

Basically: If you don’t know exactly the state of the stuff the lock is locking, how can you ever dare to call out to other code that would modify the stuff by taking the recursive lock? If you DO know exactly the state of the stuff the lock is locking, why are you holding the lock?! In other words, don’t use recursive locks.

On the plus side, it’s now easier to add a new contact, and I can decide whether to call somebody or start a chat by hovering over a contact. On the minus side, everything else.

On the plus side, it’s now easier to add a new contact, and I can decide whether to call somebody or start a chat by hovering over a contact. On the minus side, everything else.
ignorethecode on the atrocity that is Skype 5. It really is a bloated, ugly, misbehaving piece of crap software. It’s even worse than the original MSN Messenger for Mac OS, and that’s quite an achievement. (Bloated chat UIs are a pet peeve of mine; I had an argument with my friend Sterd about it back before I had successfully converted him to a Mac user (:P) using this picture comparing the space efficiency of an MSN for Windows chat window with that of Adium, and not even using one of the minimalistic Adium themes.)

Eskil Steenberg (creator of Indie MMO “Love” - which is also a Voxel world engine of sorts) has told me that he doesn’t bother with small chunks – he just has a single Vertex Array that represents an entire quadrant of his spherical world, and to get around the massive waste of space he actually has to _defrag_ his graphics memory using his own memory management functions running on his GPU, effectively pushing all the active visible triangles together, and leaving a single large clear area of graphics memory for future triangles to be placed. This is the kind of batshit crazy engine programming I’ve come to expect from Eskil, and is not for the faint of heart.

Eskil Steenberg (creator of Indie MMO “Love” - which is also a Voxel world engine of sorts) has told me that he doesn’t bother with small chunks – he just has a single Vertex Array that represents an entire quadrant of his spherical world, and to get around the massive waste of space he actually has to _defrag_ his graphics memory using his own memory management functions running on his GPU, effectively pushing all the active visible triangles together, and leaving a single large clear area of graphics memory for future triangles to be placed. This is the kind of batshit crazy engine programming I’ve come to expect from Eskil, and is not for the faint of heart.
Defcon - Minecraft + Physics = Awesome (how can you not read an article with that title?)

UIKit: Hide the keyboard without a reference to the currently focused text field

Googling for answers to UIKit or iOS/iPhone programming problems today resembles googling for answers to JavaScript problems. There is so much horribly, horribly broken code out there, being promoted as the way to do things.

Ranting aside, today’s problem is writing your own view controller container, and noticing that focused UI elements don’t dismiss their keyboard in response to viewWillDisappear: or similar. If this was MacOS, or AppStore approval didn’t exist, you’d just do [self.view.window.firstResponder resignFirstResponder]. You can’t do that though, firstResponder is private on window, don’t ask me why. cdyson37 on StackOverflow however, found the public API -[UIView(UITextField) endEditing:] hidden in a category in UITextField.h, that supposedly looks recursively through the receiver’s children for the first responder, and if found, resigns it. Perfect! A copy-pasteable code snippet for lazy googlers:

[self.view endEditing:YES]

UPDATE! Turns out I’m an idiot. While the above works and is correct, there is a better way. You don’t NEED to have access to the first responder, because you can use a nil targeted action instead, which will walk the responder chain, starting at the first responder. So a MUCH prettier way of hiding the keyboard is:

[[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];

Thanks to BigZaphod for that code snippet. I haven’t used sendAction: since I did Mac coding, before I suddenly became an almost-iOS-only coder in 2008. The responder chain is so handy, I must start using it more in my iOS coding…

no title


Nerdery at its best. No better way to put your old computers to use than to make them sing! (via Keendra)

Rasmus Andersson: Why I wrote a programmer's text editor

Rasmus Andersson: Why I wrote a programmer's text editor

rsms:

bla bla bla bla bla the less productive is the result. There’s an unfortunate common pattern when people open up a new application for the first time: They start by going into the “Preferences” UI and dig around like it was a game of Zelda. Instead Kod will have a very limited set of preferences which can be configured through a bla bla bla bla

YES! I need to do that! The preferences dialog for my next productivity app, there won’t be a standard Cocoa control in sight! It’ll be an RPG! And you have to explore the game world for *hours* to find the most obscure preferences! Want to change the default app to use for Frobnitzing? It’s right there, first room. Want to configure the font size of the auxiliary extension panel? You’re going to have AN ADVENTURE finding it.