Miscellaneous improvements.
5 // Created by Jens Alfke on 2/25/08.
6 // Copyright 2008 Jens Alfke. All rights reserved.
12 @implementation Observance
14 - (id) initWithTarget: (id)target
16 observed: (id)observed
17 keyPath: (NSString*)keyPath
18 options: (NSKeyValueObservingOptions)options
25 _keyPath = [keyPath copy];
28 options &= ~(MYKeyValueObservingOptionOnce | MYKeyValueObservingOptionDelayed);
30 [_observed addObserver: self forKeyPath: _keyPath options: options context: _action];
37 [_observed removeObserver: self forKeyPath: _keyPath];
43 @synthesize observed=_observed, keyPath=_keyPath;
46 - (void) stopObserving
48 [_observed removeObserver: self forKeyPath: _keyPath];
55 - (void) _callTargetWithChange: (NSDictionary*)change
58 [_target performSelector: _action withObject: _observed withObject: change];
59 }@catch( NSException *x ) {
60 Warn(@"Uncaught exception in -[%@<%p> %s] while observing change of key-path %@ in %@<%p>: %@",
61 _target,_target, _action, _keyPath, _observed,_observed, x);
62 [NSApp reportException: x];
67 - (void)observeValueForKeyPath:(NSString *)keyPath
69 change:(NSDictionary *)change
70 context:(void *)context
72 if( object == _observed ) {
73 if( _options & MYKeyValueObservingOptionDelayed )
74 [self performSelector: @selector(_callTargetWithChange:) withObject: change
77 [self _callTargetWithChange: change];
78 if( _options & MYKeyValueObservingOptionOnce )
89 @implementation Observer
94 return [self initWithTarget: self];
99 - (id) initWithTarget: (id)target
105 _observances = [[NSMutableArray alloc] init];
113 [self stopObserving];
114 [_observances release];
119 @synthesize target=_target;
122 - (void) observe: (id)observed
123 keyPath: (NSString*)keyPath
124 options: (NSKeyValueObservingOptions)options
127 Observance *o = [[Observance alloc] initWithTarget: _target
132 [_observances addObject: o];
137 - (void) observe: (id)observed
138 keyPath: (NSString*)keyPath
141 [self observe: observed keyPath: keyPath options: 0 action: action];
145 - (void) stopObserving
147 [_observances makeObjectsPerformSelector: @selector(stopObserving)];
148 [_observances removeAllObjects];
152 - (void) stopObserving: (id)observed
154 [self stopObserving: observed keyPath: nil];
158 - (void) stopObserving: (id)observed keyPath: (NSString*)keyPath
160 // observed or keyPath may be nil
161 for( int i=_observances.count-1; i>=0; i-- ) {
162 Observance *o = [_observances objectAtIndex: i];
163 if( (observed==nil || observed==o.observed) && (keyPath==nil || [keyPath isEqual: o.keyPath]) ) {
165 [_observances removeObjectAtIndex: i];