1 // https://github.com/objcio/issue-7-lab-color-space-explorer/blob/9551c8b6f67dd46eca91d93c0437d10ff9ee4eed/Lab%20Color%20Space%20Explorer/KeyValueObserver.m
3 // Lab Color Space Explorer
5 // Created by Daniel Eggert on 01/12/2013.
6 // Copyright (c) 2013 objc.io. All rights reserved.
9 #import "KeyValueObserver.h"
12 // Created by chris on 7/24/13.
15 #import "KeyValueObserver.h"
17 @interface KeyValueObserver ()
18 @property (nonatomic, weak) id observedObject;
19 @property (nonatomic, copy) NSString* keyPath;
22 @implementation KeyValueObserver
24 - (id)initWithObject:(id)object keyPath:(NSString*)keyPath target:(id)target selector:(SEL)selector options:(NSKeyValueObservingOptions)options;
29 NSParameterAssert(target != nil);
30 NSParameterAssert([target respondsToSelector:selector]);
34 self.selector = selector;
35 self.observedObject = object;
36 self.keyPath = keyPath;
37 [object addObserver:self forKeyPath:keyPath options:options context:(__bridge void *)(self)];
42 + (NSObject *)observeObject:(id)object keyPath:(NSString*)keyPath target:(id)target selector:(SEL)selector __attribute__((warn_unused_result));
44 return [self observeObject:object keyPath:keyPath target:target selector:selector options:0];
47 + (NSObject *)observeObject:(id)object keyPath:(NSString*)keyPath target:(id)target selector:(SEL)selector options:(NSKeyValueObservingOptions)options __attribute__((warn_unused_result));
49 return [[self alloc] initWithObject:object keyPath:keyPath target:target selector:selector options:options];
52 - (void)observeValueForKeyPath:(NSString*)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void*)context
54 if (context == (__bridge void *)(self)) {
55 [self didChange:change];
59 - (void)didChange:(NSDictionary *)change;
61 id strongTarget = self.target;
62 #pragma clang diagnostic push
63 #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
64 [strongTarget performSelector:self.selector withObject:change];
65 #pragma clang diagnostic pop
70 [self.observedObject removeObserver:self forKeyPath:self.keyPath];