-
Notifications
You must be signed in to change notification settings - Fork 2
/
JLKVObserver.m
86 lines (62 loc) · 1.69 KB
/
JLKVObserver.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
74
75
76
77
78
79
80
81
82
83
84
85
86
//
// JLKVObserver.m
// Celestial
//
// Created by jlopez on 9/8/10.
// Copyright 2010 __MyCompanyName__. All rights reserved.
//
#import "JLKVObserver.h"
@implementation JLKVObserver
@synthesize observedObject;
@synthesize keyPath;
@synthesize observingOptions;
@synthesize allowNestedCalls;
- (id)init {
if (self = [super init]) {
observingOptions = NSKeyValueObservingOptionInitial;
}
return self;
}
- (void)dealloc {
[self stopObserving];
[super dealloc];
}
- (void)startObservingObject:(id)object keyPath:(NSString *)keyPath_ block:(void (^)())block_ {
NSAssert(keyPath_ != nil, @"keyPath must not be nil");
NSAssert(block_ != nil, @"block must not be nil");
if (object == observedObject && [keyPath_ isEqualToString:keyPath] && block == block_)
return;
[self stopObserving];
if (object == nil)
return;
observedObject = [object retain];
keyPath = [keyPath_ retain];
block = [block_ copy];
[observedObject addObserver:self forKeyPath:keyPath options:observingOptions context:self];
}
- (void)stopObserving {
if (observedObject) {
[observedObject removeObserver:self forKeyPath:keyPath];
[observedObject release];
observedObject = nil;
[keyPath release];
keyPath = nil;
[block release];
block = nil;
}
}
- (BOOL)isObserving {
return observedObject != nil;
}
- (void)observeValueForKeyPath:(NSString *)keyPath_ ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if (self == context) {
if (isNested && !allowNestedCalls)
return;
isNested = YES;
block();
isNested = NO;
}
else
[super observeValueForKeyPath:keyPath_ ofObject:object change:change context:context];
}
@end