tags:

views:

233

answers:

3

I am building a Cocoa desktop application. I want to know when a NSView's isHidden status has changed. So far using target/action doesn't help, and I can't find anything in NSNotification for this task. I would like to avoid overriding the setHidden method, because then I'll have to override all the NSView derived class that I am using.

UPDATE: I ended up using KVO. The path for "isHidden" is "hidden", probably because the setter is "setHidden".

A: 

Could you override the setter method for the hidden property so that it will trigger some custom notification within your application?

Tim
I am avoiding this method. I forgot to add this detail to my question. Thanks for reminding me.
phi
+2  A: 

You could use Key-Value Observing to observe the isHidden property of the NSView(s). When you receive a change notification from one of these views, you can check if it or one of its superviews is hidden with -isHiddenOrHasHiddenAncestor.

A word of warning: getting Key-Value Observing right is slightly tricky. I would highly recommend reading this post by Michael Ash, or using the -[NSObject gtm_addObserver:forKeyPath:selector:userInfo:options] method from the NSObject+KeyValueObserving category from the Google Toolbox for Mac.

Barry Wark
A: 

More generally, one can override viewWillMoveToWindow: or the other related methods in NSView to tell when a view will actually be showing (i.e. it's window is in the window display list AND the view is not hidden). Thus the dependency on KVO for the 'hidden' key used above is removed, which only works if setIsHidden has been called on that view. In the override, 'window' (or [self window]) will indicate whether the view is being put into a visible view hierarchy (window is non-nil) or being taken out of it (window is nil).

I use it for example to start/stop a timer to update a control from online data periodically - when I only want to update while the control is visible.

cocteau