Code for key-value observing can be very complicated and difficult to maintain. Today I came across a set of lightweight helper classes by James Montgomerie that greatly simplify KVO and KVB called THObserversAndBinders.
Here’s how it works (taken from readme):
- – Observers are represented by simple, lightweight THObserver objects that are constructed with an object to observe, a keypath to observe on the object, and a block or target-action pair to call when the observed value changes.
- – Optionally, you can also pass arbitrary Cocoa KVO options.
- – The block or action can, again optionally, be passed the old and new value, or a whole Cocoa KVO change dictionary.
- – To keep code clean, there’s also an option to use “value action” target-action callbacks that don’t get passed the observed object and keypath like regular actions, but instead just get passed the new, or old and new, values.
- – The observation’s lifetime is entirely managed by the THObserver object. Keep it around, the observation is alive. Release it, and the observations stop. You can also optionally stop them manually by calling -stopObserving.
- – The observed object and the target are weakly referenced, so nothing’s going to blow up if you release things in the wrong order, or if your observer is being held in an autorelease pool somewhere (this isn’t something I think should be necessary, but it’s nice to have).
You can find THObserversAndBinders on Github here.
You can view examples showing exactly how simple the code is here.
Definitely quite a bit of thought was put into creating these classes making for a very clean way to do KVO.
Submit A Resource
Have you created a useful tutorial, library or tool for iOS development that you would like to get in front of our 300,000+ monthly page views from iOS developers?
You can submit the url here.
The resources we feel will appeal to our readers the most will be posted on the front page.