-
Notifications
You must be signed in to change notification settings - Fork 25
/
KeyValueObserver.m
73 lines (61 loc) · 2.11 KB
/
KeyValueObserver.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
//
// KeyValueObserver.m
// Lab Color Space Explorer
//
// Created by Daniel Eggert on 01/12/2013.
// Copyright (c) 2013 objc.io. All rights reserved.
//
#import "KeyValueObserver.h"
//
// Created by chris on 7/24/13.
//
#import "KeyValueObserver.h"
@interface KeyValueObserver ()
@property (nonatomic, weak) id observedObject;
@property (nonatomic, copy) NSString* keyPath;
@end
@implementation KeyValueObserver
- (id)initWithObject:(id)object keyPath:(NSString*)keyPath target:(id)target selector:(SEL)selector options:(NSKeyValueObservingOptions)options;
{
if (object == nil) {
return nil;
}
NSParameterAssert(target != nil);
NSParameterAssert([target respondsToSelector:selector]);
self = [super init];
if (self) {
self.target = target;
self.selector = selector;
self.observedObject = object;
self.keyPath = keyPath;
[object addObserver:self forKeyPath:keyPath options:options context:(__bridge void *)(self)];
}
return self;
}
+ (NSObject *)observeObject:(id)object keyPath:(NSString*)keyPath target:(id)target selector:(SEL)selector __attribute__((warn_unused_result));
{
return [self observeObject:object keyPath:keyPath target:target selector:selector options:0];
}
+ (NSObject *)observeObject:(id)object keyPath:(NSString*)keyPath target:(id)target selector:(SEL)selector options:(NSKeyValueObservingOptions)options __attribute__((warn_unused_result));
{
return [[self alloc] initWithObject:object keyPath:keyPath target:target selector:selector options:options];
}
- (void)observeValueForKeyPath:(NSString*)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void*)context
{
if (context == (__bridge void *)(self)) {
[self didChange:change];
}
}
- (void)didChange:(NSDictionary *)change;
{
id strongTarget = self.target;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
[strongTarget performSelector:self.selector withObject:change];
#pragma clang diagnostic pop
}
- (void)dealloc;
{
[self.observedObject removeObserver:self forKeyPath:self.keyPath];
}
@end