Skip to content

Instantly share code, notes, and snippets.

@pala
Created February 10, 2014 19:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pala/8922410 to your computer and use it in GitHub Desktop.
Save pala/8922410 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