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

kentucky durby

May 3 is the date of kentucky derby 2014 the link is here. http://www.kentuckyderby2014s.com Happy derby

by Unregistered Visitor on 04/23/14

Your understanding

Your understanding with this topic will come via obviously in the following paragraphs. I enjoy look at this type of content articles, I think you'll may up-date this.
Apple mac accessories reseller in delhi and Turnkey Solution providers

by Unregistered Visitor on 06/03/14

leading manufacturer

DGGP Pvt. Ltd. is a leading manufacturer of Guar Fast Hydration Polymers used in Gas Oil Fields fracturing Industry in the world.
Natural polymers manufacturers and suppliers
Shell Energy

by Unregistered Visitor on 06/04/14

the update

For me this update is really nice and I will use it for sure! Thank you for the advice! www.yachtbooker.de

by dave panda on 06/11/14

good code

I will try to integrate it with my previous code, let's hope to see improvements! www.rechtsanwalt-tipps.de

by Unregistered Visitor on 06/13/14

do it

I will use it and do it like you said! Thanks! http://www.yachtcharteritalien.org

by Unregistered Visitor on 06/16/14

well said

Today most of students and essay learners want best essay writing services, because of i give best college essay writing services. These provides unique essays every one with low costs.

by Unregistered Visitor on 06/17/14

good code

this is nice, I can work just fine with this strategy, at least I will try! visit link

by Unregistered Visitor on 06/17/14

great

I will use a similar code for my site, let's hope that I can integrate it! Google+

by Unregistered Visitor on 06/19/14

worldly

Entrants reach hardly worldly how to employment a elementary spreadsheet, besides retire having scraped underlying information eccentric the Tangle, built their chief account outline, their primordial information visualization webcam

by Unregistered Visitor on 06/26/14

primordial

If for some brain you desire to unearth absent locksmith Basildon the kvo complain you embrace has been released primordial you can monitor the isValid accessor

by Unregistered Visitor on 07/02/14

Bio products

Hello! Thanks for your post! It's really very interesting. If you are looking for some interesting information, please visit Bio products

by Unregistered Visitor on 07/10/14

Wire line core Barrels

One of these is Creatine Internet marketing. People want not look for thoroughly to know about their desired manufacturer. Wire line core Barrels

by Unregistered Visitor on 07/11/14

Softy ice cream machine

Hmm it seems like your site ate my first comment (it was extremely long) so I guess I’ll just sum it up what I had written and say, I’m thoroughly enjoying your blog. I as well am an aspiring blog writer but I’m still new to the whole thing. Do you have any recommendations for newbie blog writers? I’d really appreciate it. Softy ice cream machine

by Unregistered Visitor on 07/11/14

Bromoethyl Benzaldehyde

my buddy's step-aunt makes $66 an hour on the computer. She has been without work for five months but last month her payment was $15155 just working on the computer for a few hours. Go to this web site and read more Bromoethyl Benzaldehyde Methoxy Decane

by Unregistered Visitor on 07/11/14

Gloves exporters

Well I think a found a solution, you need to delete the columns and add custom ones with the exact names of the old ones.. that seems to solve the problem for now Caps exporters Gloves exporters

by Unregistered Visitor on 07/11/14

Stainless steel kitchen wares

Super article, je le bookmarque et j’en parle autour de moi, merci ;) Stainless steel kitchen wares Water dispensers supplier

by Unregistered Visitor on 07/11/14

monu

Summarize people create make inside of Support Needs Brilliance throughout expansion modified acquiring dominions about the ruler's berth. freedebtconsolidationquotes.com

by Unregistered Visitor on 07/16/14

Appreciation to the Author.

Firstly, Appreciation to the Author. Because, i searched for around four days for this kind of post which explains the programming of PMPKV Observation, but found none. Finally now, I found this. Thanks. Regards, clinkle

by Unregistered Visitor on 07/17/14

compr

All of us comprehend acquired caretaker book stretches effectively it is possible to concrete floor position within starts to get genuines incredible. iphone 6 precio

by Unregistered Visitor on 07/19/14

age

Book publicised agencies are usually unsurprisingly obtainable in the world wide web likewise your diary manuscript usefulnesss downcast an indellible predict during my standing. Body Firming Cream

by Unregistered Visitor on 07/23/14

Nice post

It truly is very much exciting to me to write down some of my own trial and error ideals with regards to some of my own online favored DOMESTIC WIRES

by Unregistered Visitor on 07/24/14

great

The website is looking bit flashy and it catches the visitors eyes. Design is pretty simple and a good user friendly interface. hair transplantation

by Unregistered Visitor on 07/24/14

fabulous

I am sure that this could be a big help for all of us the drupal users. This is also going to help those beginners or just started to learn drupal.

by Unregistered Visitor on 07/24/14

fantastic

I have an interest in that book but my problem is they have available book but not like yours. Dentist in Ranchi

by Unregistered Visitor on 07/24/14

informative

I do agree with melanie that somehow for us the beginners, we could use some of these books and ebooks that we bought online. Moulding works in Hyderabad

by Unregistered Visitor on 07/24/14

great info

Now I do love this drupal themes books here. Well, in my situation I think I should buy more drupal tutorial books or even ebooks that I could use for my own resources. pcc Hyderabad

by Unregistered Visitor on 07/24/14

good info

Somehow this is a really good strategy and we should do it. I am sure that we iwll have excellent results. duplex filters manufacturers in Hyderabad

by Unregistered Visitor on 07/24/14

amazing

Even like this could be a amazing screen notion. It may be fairly engaging indeed. Thank you for your facts. I definitely like to research details. 3d ground scanners

by Unregistered Visitor on 07/24/14

Thanks

Thanks for the script as it brings me a lot of joy that I could get some one-stop solution to my KVO crashing. I appreciate the author for helping out a lot of people like me. Looking forward for much more similar useful posts. I'll keep visiting. Regards, where to buy argan oil for my skin

by Unregistered Visitor on 07/26/14

helped

If for some reason you want to find out if the Cool cufflinks object you hold has been released .

by Unregistered Visitor on 07/28/14

Add comment