Skip to content

Instantly share code, notes, and snippets.

@atnan
Created December 23, 2010 04:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atnan/752571 to your computer and use it in GitHub Desktop.
Save atnan/752571 to your computer and use it in GitHub Desktop.
#import "NDVKVOMacros.h"
@implementation Foo
@synthesize bar;
- (id)init {
self = [super init];
if (self != nil) {
OBSERVE_CHANGES_FOR_PROPERTIES(@"bar");
}
return self;
}
- (void)barDidChangeWithOldValue:(id)oldValue
newValue:(id)newValue {
// Handle the new value
}
SYNTHESIZE_PROPERTY_CHANGE_OBSERVER();
@end
//
// NDVKVOMacros.h
// NDVKit
//
// Created by Nathan de Vries on 25/08/10.
// Copyright 2010 Nathan de Vries. All rights reserved.
//
#define OBSERVE_CHANGES_FOR_PROPERTIES(...) \
\
for (NSString* property in [NSArray arrayWithObjects:__VA_ARGS__, nil]) { \
[self addObserver:self \
forKeyPath:property \
options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld) \
context:NULL]; \
}
#define SYNTHESIZE_PROPERTY_CHANGE_OBSERVER() \
\
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { \
if ([[change valueForKey:NSKeyValueChangeKindKey] integerValue] == NSKeyValueChangeSetting) { \
SEL changeSelector = NSSelectorFromString([keyPath stringByAppendingString:@"DidChange"]); \
SEL changeSelectorWithValues = NSSelectorFromString([keyPath stringByAppendingString:@"DidChangeWithOldValue:newValue:"]); \
\
if ([self respondsToSelector:changeSelector]) { \
[self performSelector:changeSelector]; \
\
} else if ([self respondsToSelector:changeSelectorWithValues]) { \
id oldValue = [change valueForKey:NSKeyValueChangeOldKey] ?: nil; \
id newValue = [change valueForKey:NSKeyValueChangeNewKey]; \
\
oldValue = (oldValue == [NSNull null]) ? nil : oldValue; \
\
[self performSelector:changeSelectorWithValues withObject:oldValue withObject:newValue]; \
} \
} \
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment