Elegant Data Binding in Objective-C with ReactiveCocoa

If you’re developing apps for iOS then you should be (painfully) familiar with the Key-Value Observing (KVO) pattern. Says Chief NSHipster Matt Thompson about KVO:

Ask anyone who’s been around the NSBlock a few times: Key-Value Observing has the worst API in all of Cocoa. It’s awkward, verbose, and confusing. And worst of all, its terrible API belies one of the most compelling features of the framework.

Unfortunately, KVO seems to be the best way to natively achieve data binding on the iOS platform.

Let’s say that you have a first name label in a view that you want to hook up to a first name property of a Person object. Typically you would do something like this:

Even with only one property, this looks rather ugly. Now add last name, address and phone number to the list of requirements, and imagine the result.

Another caveat of KVO is that you need to take great care to remove any observer you add, to avoid weirdness and crashing.

Here’s how it could look with ReactiveCocoa:

Ah, much better! And no need for removing observers or worrying about crashes. I can appreciate this on a very deep emotional level, after having playing around with KVO inside volatile UITableViewCells.

You may recall my previous blog post about third party dependencies. Another argument against using a third party dependency is that you’re only going to use a minuscule part of it. I think in this case, even if you’re only going to use ReactiveCocoa for data binding, it is warranted.

I just started scratching the surface of ReactiveCocoa, and so-called Functional Reactive Programming.

I urge you to check out the tutorials on raywenderlich.com, if you’re curious about ReactiveCocoa:

Or watch this tech-talk covering roughly the same material.

Legg inn en kommentar