Begin main content

PMPKVObservation – Yet Another KVO-improvement project

If you’re reading this then you’re probably as frustrated by seemingly random KVO crashes and/or the pain of huge if/else blocks in your observers. I’ve never been happy with the other KVO-improvement classes I’ve seen, and never having had any bright insights myself I kept doing things the normal way. This becomes especially painful with things like view based NSTableViews when you are re-using objects and so need to observe a new object, being very careful to un-observe the prior object (unless it’s been released, which you need to either track yourself if you can, or retain it, which has its own problems).


It was clear that the dealloc swizzling approach of Mike Ash’s MAKVONotificationCenter was unavoidable, but I didn’t like the complexity. Recently Gwynne Raskind posted a somewhat updated MAKVONotificationCenter which sparked some discussion, including a comment discussing SPKVONotificationCenter by Joachim Bengtsson. Joachim’s brainwave was that observations should be modelled as standalone objects and simply managing the lifecycle of that object appropriately should remove the observation. Clean and simple.

Except it’s not quite that simple because you still need to swizzle the dealloc of the observed object since it can go away at any time. And as much as I love a good macro as much as the next hacker, Joachim’s $depends() macro looks about as much fun as a turing complete makefile.

Enter PMPKVObservation!

Include PMPKVObservation.m and .h in your project, then do something like:

#import"PMPKVObservation.h"

@interface PMPKVOTests ()
@property (retain) PMPKVObservation * kvo;
@end

@implementation PMPKVOTests
@synthesizekvo = _kvo;

- (void)observationFired:(PMPKVObservation *)observationchanges:(NSDictionary *)changes;
{
NSLog(@"observation fired for object: %@ keyPath: %@ changes: %@",
observation.observee,
observation.keyPath,
changes);
}

- (void)selectorObservation
{
self.kvo = [PMPKVObservation observe:anObjectToObserve
observer:self
selector:@selector(observationFired:changes:)
keyPath:@"observeMe"
options:0];
}

- (void)blockObservation
{
self.kvo = [PMPKVObservation observe:anObjectToObserve
keyPath:@"observeMe"
options:0
callback:^(PMPKVObservation *observation, NSDictionary *changeDictionary) {
NSLog(@"observation fired for object: %@ keyPath: %@ changes: %@",
observation.observee,
observation.keyPath,
changes);
}];
}

- (void)dealloc
{
[ _kvo release];

[super dealloc];
}

@end

The options and change dictionary are as per normal KVO. You need to be wary of the block causing retain cycles of self as usual.

Unlike MAKVONotificationCenter and others, you are responsible for managing the lifecycle of the kvo object – when it is dealloc-ed the observation will be removed. Like MAKVONotificationCenter, a minimum of magic is used to swizzle the dealloc method of the observed object and remove the observation if it still exists (tracked via an associated NSHashTable). If for some reason you want to find out if the kvo object you hold has been released early you can check the isValid accessor (which you can observe with KVO).

Caveats

  1. While I am using this in a client project, that project has not yet shipped so I can’t promise wide-spread testing. Take a look at the tests in the test app and if you are using scenarios that you don’t thing are tested pull requests are welcome!
  2. I haven’t tried this under ARC, but I think I’ve made PMPKVObservation.m so it will compile and work as-is (the same can’t be said for the test app). Please let me know how you go.
  3. No attempt is made to stop you changing the observed object etc. after creation, but doing so isn’t going to be very effective…

Repository: https://github.com/aufflick/PMPKVObservation

06:49 PM, 13 Mar 2012 by Mark Aufflick Permalink

код тн вэд

Advantageously, the article is really the best on this notable topic. I harmonize with your conclusions and will thirstily look forward to your approaching updates код тн вэд

by Unregistered Visitor on 10/21/14

Nice post

This post is very helpful for me. I learned a lot. Thanks for sharing. my web

by Unregistered Visitor on 10/22/14

works

It is a building a web page, functionality first prior to the interface. It is more important that this program How apple pay works with passbook? works in lieu of beauitifying it without having functionality. Great post!

by Unregistered Visitor on 10/24/14

rock

Really yielding trifling undivided school terminate up soul requiring a dispatch on the thread attendant in precept to uproot despite an appropriate retain slightly moreover middle comprehends in directive to obsolesce later. car insurance

by Unregistered Visitor on 10/27/14

jack

backlinks

by Unregistered Visitor on 10/27/14

rock

Your latest tell gives drag mass support on where to explore a fabulous bandy musician that might be tried stationary useful. crowdfunding software

by Unregistered Visitor on 10/31/14

jogos de moto

i really liked this a lot novos jogos de moto

by Unregistered Visitor on 10/31/14

rock

My husband too i gain also been knotty to full my possess apparatus to receive a outlaw in adjunct My occupation is onto operating unaccustomed fellow of sundry. Made In Japan

by Unregistered Visitor on 11/01/14

great

well wow this was really amazing guys low calorie recipes

by Unregistered Visitor on 11/02/14

WordPress restaurant themes

Hi buddy, your blog's design is simple and clean and i like it. Your blog posts are superb. Please keep them coming. Greets!!! WordPress restaurant themes

by Unregistered Visitor on 11/06/14

zeeshan1

I am always searching online for articles that can help me. There is obviously a lot to know about this. I think you made some good points in Features also. Keep working, great job! http://binary-options-reviews.com/text.php?lang=heb&id=9&sid=28

by ahmed raza on 11/07/14

jackson

This is my initial span i stopover here. I discovered so numerous entertaining force in your blog, essentially its palaver. From the tons of notes on your doctrines, I shot I am nay the except individual holding total the idle here! Fulfill up the amazing process. FreeDebtConsolidationQuotes.com

by Unregistered Visitor on 11/09/14

jack

I would also motivate just about wisdom teeth removal lauderhill every person to save this web page for any favorite assistance to assist posted the appearance.

by Unregistered Visitor on 11/10/14

Nice Post

I was searching this type of information from a week. Now I am happy to read it. It Solve may problem. rubber stable mats for sale

by Unregistered Visitor on 11/12/14

Good One

Simply great work. I appreciate the efforts that you make spreading this information. ground reinforcement matting

by Unregistered Visitor on 11/12/14

I like It

I discovered this particular write-up being really educational. Many thanks pertaining to widening my personal understanding of this particular issue. Without doubt its an excellent write-up likewise. Thanks. gymnasticmatsco

by Unregistered Visitor on 11/12/14

Really Amazing

This subject has interested me for quite some time. I have just started researching it on the Internet and found your post to be informative. Thanks. cheap garage flooring tiles

by Unregistered Visitor on 11/12/14

use

This blog is very useful information for me and guidance. This is a fantastic alternative to medical and chemical treatments. Thanks for sharing this information here. charbon chicha

by Unregistered Visitor on 11/13/14

raido

Year 2013 has been quite eventful. Broadcast consultancy

by Unregistered Visitor on 11/14/14

Emulatore 3DS per PC

Nintendo ha tenuto un flusso dal vivo ieri sui prossimi giochi per la console Nintendo 3DS, Nintendo Wii e 2DS U. Anche se, Nintendo ha annunciato ulterior Emulatore 3DS per PC informazioni Amiibo per il Wii U la chiara attenzione si è concentrata sui titoli per Nintendo 3DS e Nintendo 2DS.

by Unregistered Visitor on 11/14/14

Emulatore 3DS per PC

A volte, la vita di portare giù. In generale, si potrebbe andare a meraviglia, ma poi un paio di cose che succedono e il giorno si scende. Le cose non stanno Emulatore 3DS per PC andando la tua strada, e tutto solo si sente fuori. Potrebbe essere solo ti sei svegliato dalla parte sbagliata del letto: ...

by Unregistered Visitor on 11/14/14

zeeshan

Awesome material! Thanks a lot, dude, for giving this so good material to us. I've just recently completed one of my projects due to the information from this post. Thanks man, once again! http://www.fitness-products-reviews.com

by ahmed raza on 11/15/14

Sutopo

thanks nice post homestay Kursus SEO Toko Komputer Kursus Bahasa Inggris

by Unregistered Visitor on 11/15/14

Sasuke

thanks nice post rental mobil solo sewa mobil jogja sewa bus yogyakarta/ rental mobil jogja

by Unregistered Visitor on 11/15/14

joss

thanks nice post Setia Furqon hotel di jogja

by Unregistered Visitor on 11/15/14

oxygen miracle cure reviews

A reliable blog always comes-up with new and exciting information and while reading I have experience that this blog is really have all those quality that qualify a blog to be a good one oxygen miracle cure reviews

by Unregistered Visitor on 11/22/14

zeeshan

Phoenix Tile Cleaning Extraordinary, This particular net page is genuinely exciting and delight to learn. I'm a colossal fan from the subjects specified. Surprise Tile Cleaning

by ahmed raza on 11/23/14

Add comment