Skip to content

Instantly share code, notes, and snippets.

@yonglam
Forked from pala/TZReceptionist.h
Created February 2, 2019 11:59
Show Gist options
  • Save yonglam/81682de12714b5d7b4dd2b51e52c276c to your computer and use it in GitHub Desktop.
Save yonglam/81682de12714b5d7b4dd2b51e52c276c to your computer and use it in GitHub Desktop.
Receptionist Pattern
#import <Foundation/Foundation.h>
typedef void (^RCTaskBlock)(NSString *keyPath, id object, NSDictionary *change);
@interface TZReceptionist : NSObject
+ (id)receptionistForKeyPath:(NSString *)path
object:(id)obj
queue:(NSOperationQueue *)queue
task:(RCTaskBlock)task;
@end
#import "TZReceptionist.h"
@interface TZReceptionist ()
@property (strong, nonatomic) id observedObject;
@property (copy, nonatomic) NSString *observedKeyPath;
@property (copy, nonatomic) RCTaskBlock task;
@property (strong, nonatomic) NSOperationQueue *queue;
@end
@implementation TZReceptionist
+ (instancetype)receptionistForKeyPath:(NSString *)path object:(id)obj
queue:(NSOperationQueue *)queue task:(RCTaskBlock)task {
TZReceptionist *receptionist = [TZReceptionist new];
receptionist.task = task;
receptionist.observedKeyPath = path;
receptionist.observedObject = obj;
receptionist.queue = queue;
[obj addObserver:receptionist forKeyPath:path
options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:0];
return receptionist;
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
change:(NSDictionary *)change context:(void *)context {
[self.queue addOperationWithBlock:^{
self.task(keyPath, object, change);
}];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment