-
-
Save yonglam/81682de12714b5d7b4dd2b51e52c276c to your computer and use it in GitHub Desktop.
Receptionist Pattern
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 (^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 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