Created
February 10, 2014 19:23
-
-
Save pala/8922410 to your computer and use it in GitHub Desktop.
Receptionist Pattern
This file contains hidden or 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 (^RCTaskBlock)(NSString *keyPath, id object, NSDictionary *change); | |
@interface TZReceptionist : NSObject | |
+ (id)receptionistForKeyPath:(NSString *)path | |
object:(id)obj | |
queue:(NSOperationQueue *)queue | |
task:(RCTaskBlock)task; | |
@end |
This file contains hidden or 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 "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