Created
April 5, 2015 20:22
-
-
Save randombrein/744e7760f0b9659e1b91 to your computer and use it in GitHub Desktop.
Receiptionist patter over KVO
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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