version bump
[ShaarliOS.git] / swift4 / ShaarliOS / 3rd / KeyValueObserver.m
blobd57bb1021631154d82f1794b89483f7f7c05ffbd
1 //  https://github.com/objcio/issue-7-lab-color-space-explorer/blob/9551c8b6f67dd46eca91d93c0437d10ff9ee4eed/Lab%20Color%20Space%20Explorer/KeyValueObserver.m
2 //  KeyValueObserver.m
3 //  Lab Color Space Explorer
4 //
5 //  Created by Daniel Eggert on 01/12/2013.
6 //  Copyright (c) 2013 objc.io. All rights reserved.
7 //
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;
20 @end
22 @implementation KeyValueObserver
24 - (id)initWithObject:(id)object keyPath:(NSString*)keyPath target:(id)target selector:(SEL)selector options:(NSKeyValueObservingOptions)options;
26     if (object == nil) {
27         return nil;
28     }
29     NSParameterAssert(target != nil);
30     NSParameterAssert([target respondsToSelector:selector]);
31     self = [super init];
32     if (self) {
33         self.target = target;
34         self.selector = selector;
35         self.observedObject = object;
36         self.keyPath = keyPath;
37         [object addObserver:self forKeyPath:keyPath options:options context:(__bridge void *)(self)];
38     }
39     return 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];
56     }
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
68 - (void)dealloc;
70     [self.observedObject removeObserver:self forKeyPath:self.keyPath];
73 @end