Skip to content

Instantly share code, notes, and snippets.

@randombrein
Created April 5, 2015 20:22
Show Gist options
  • Save randombrein/744e7760f0b9659e1b91 to your computer and use it in GitHub Desktop.
Save randombrein/744e7760f0b9659e1b91 to your computer and use it in GitHub Desktop.
Receiptionist patter over KVO
#import <Foundation/Foundation.h>
typedef void (^ReceptionistTask)(NSString *keyPath, id obj, NSDictionary *change);
@interface Receptionist : NSObject
+ (instancetype)receptionistForObject:(id)obj withKeyPath:(NSString*)keyPath withQueue:(NSOperationQueue*)queue withTask:(ReceptionistTask)task;
@end
@implementation Receptionist {
id _observerdObj;
NSString *_observerKeyPath;
NSOperationQueue *_queue;
ReceptionistTask _task;
}
+ (instancetype)receptionistForObject:(id)obj withKeyPath:(NSString*)keyPath withQueue:(NSOperationQueue*)queue withTask:(ReceptionistTask)task {
Receptionist *receptionist = [Receptionist new];
receptionist->_observerdObj = obj;
receptionist->_observerKeyPath = keyPath;
receptionist->_queue = queue;
receptionist->_task = [task copy];
[obj addObserver:receptionist forKeyPath:keyPath options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:NULL];
return receptionist;
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
[_queue addOperationWithBlock:^{
_task(keyPath, object, change);
}];
}
- (void)dealloc {
[_observerdObj removeObserver:self];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment