Re: KVO Question: How to programmatically determine if one object is observing another on a keyPath and context?
Re: KVO Question: How to programmatically determine if one object is observing another on a keyPath and context?
- Subject: Re: KVO Question: How to programmatically determine if one object is observing another on a keyPath and context?
- From: Mike Abdullah <email@hidden>
- Date: Sun, 09 Sep 2012 14:41:57 +0100
On 9 Sep 2012, at 10:32, Motti Shneor <email@hidden> wrote:
> Hi everyone. This seems a novice question, but I could not find any high-level approach for that.
>
> Some details of my special need: I have an NSViewController subclass, that should observe some attribute of its representedObject.
>
> However, the representedObject may change to another, become nil etc.
>
> In addition, I have server-born triggers also affecting (stop/start) observing that keyPath.
>
> I'd like to code this in a "local" manner -- meaning, when a change occurs - check if I'm already observing/not-observing the key-path, and either start, stop or do nothing with the observation. In the -(void)dealloc of my NSViewController, i'd also like to remove myself as an observer from whatever objects I'm observing.
>
> I currently use state iVars that record the state of observation, but that's ugly. I 'd like something like
>
>
> - (NSUInteger)isObserver:(id)object on keyPath:(NSString *)keyPath withContext:(void *)context]; // the returned number is the count of same observances with 0 as not-observing).
>
> and something like
>
> - (BOOL)removeObserver:(id)object; // where I instruct the receiver to remove object as an observer, on all key-paths and contexts. should return YES if object was an observer, and was removed, NO otherwise.
>
> Any ideas?
The KVO system does not support introspection. It is also not designed in such a way where a singly -removeObserver: method would be possible.
The intention is that observers just play by very simple rules. Add themselves at the start of observation, and remove themselves at the end. The system takes care of handling multiple observers neatly internally. By your description, it sound like in your view controller's init method you want to do this:
[self addObserver:self forKeyPath:@"representedObject.someAttribute" …
Tear it down again in -dealloc.
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden