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

Nice post

Guar protein offer a wide selection of products for your specific requirements. Established in the year 2008, we are one of the leading Manufacturer, Exporter and Supplier of Compound Guar Protein Meal Feeds and Poultry Feeds.
microlam Roasted korma and Guar korma and Organic animal feed

by Unregistered Visitor on 09/17/14

exactly how high interest rates

The maximum size of the money borrowed from the loan? – Your vehicle manual one common industry credit ratings to determine the market value of instant loans auto title, you can make a fair assessment of loans. in General, a change of $ 1 to $ 600 credit is 2.500. quick loans So, exactly how high interest rates? -Release the interest rate for a short cheap loans period of time available. for example, during the month of 25% will be displayed as a single loan interest rate of rate of 300 percent, depending on the means loans without credit check but. year. Auto title loan lenders to provide credit to them for a period of less than thirty (30) days of the end of the month, so it is common that a transfer interest and debt payments in the next month to get a loan is deemed to be monthly loans interested in debt so you can receive credit if the $ 150 to $ 600, for a total of about $ 750. at the end of the month is just $ 150, in the sense of debt and pay $ 750 next month.

by Unregistered Visitor on 09/20/14

nice

earn online

by Unregistered Visitor on 09/21/14

you can see the

you can see the partition you should also apply to pay less than if payday loans direct lenders you pay off the balance every month by selling forward interest rates next month in the amount of 15% of the no guarantor loans rest after the payment. Annual percentage yield (APY), checking, savings, or other payday loan no credit check type of account, pay attention to the term used to describe the interest he pays in funds amount first and account APY home. is always payday loans no credit check Monday through April is better. this interest daily average balance of profits, daily, monthly, or quarterly, or composite short term loans uk .APY: the amount of calculated previously, there is a high amount and therefore achieve balance APY can be debited from loans against car the account, thus, apart from the interest, he added., deposit interest rate is calculated each time better than the previous.

by Unregistered Visitor on 09/21/14

To compensate

To compensate property development finance debt loans helpful and very friendly concentrations.By a very cheap price to provide the safest choice, loans.I'll finish Application Procedures Later changed to online loans.Only quick loans, credit transactions, please forex robot blame the total additional cost.This is not only beneficial to the borrower, is a low cost means of capital is very popular.I have to pay the best forex trading platform I use a personal credit N all aspects of British society.You will not be able to speak in accordance with their dreams of credit.As its name implies, commercial asset finance without collateral to start another list or a new business or expand their business.In order to loans for people on benefits meet all the actions of the financial institutio No, sudden financial difficulties, in order instant payday loans to provide unsecured loans.

by Unregistered Visitor on 09/26/14

Dermalogica

Hi! This is my first visit to your blog! We are a team of volunteers and new initiatives in the same niche. Blog gave us useful information to work. You have done an amazing job. Dermalogica

by Unregistered Visitor on 09/26/14

Mediation Training

You need to experience the aide to contain to huddle each college you are applying to–in as numerous dominion as you perhaps can–plus self-possessed your synthesiss about yourself, fixed with a develop sagacity of which university you are talking to whereas you simple that school’s auxiliarys. Mediation Training

by Unregistered Visitor on 10/01/14

Add comment