Sneaky Key-Value Observing
Sneaky Key-Value Observing
- Subject: Sneaky Key-Value Observing
- From: Josh Anon <email@hidden>
- Date: Tue, 10 Feb 2004 14:18:37 -0800
Here's an interesting problem--I have an object that needs to know when
the visible tab changes. It can't be the tab view delegate, as it's
supposed to be a bit abstracted from the app, and the usual
viewDidMoveToSuperview stuff won't work, as this isn't/can't be a view
subclass. It's also not practical to make all the views in the tab
view subclass my view.
I played with NSViewFocusDidChangeNotification, but that gets sent
before superview gets changed, so you don't know which was
added/removed from the tab.
I can get this working by using poseAsClass, but I had a better
idea--why not use key-value observing on the superview method (can it
even be used for this)?
In my test app, subview1 and subview2 are a text view and an image
view, and they're both in a tab view. I added this code to
awakeFromNib:
[subview1 addObserver:self
forKeyPath:@"superview"
options:NSKeyValueObservingOptionNew
context:@selector(superviewChanged:)];
[subview2 addObserver:self
forKeyPath:@"superview"
options:NSKeyValueObservingOptionNew
context:@selector(superviewChanged:)];
and this in general:
@implementation NSView (AppControllerExt)
-(void)setSuperview:(NSView*)v {
[v addSubview:self];
}
@end
then, I added these methods:
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context {
SEL sel = (SEL)context;
[self performSelector:sel withObject:object];
}
-(void)superviewChanged:(id)obj {
NSLog(@"superview changed for %@", obj);
}
However, observeValueForKeyPath:... never gets called. I'm sure that
I'm missing something simple, but I'm not seeing it. Any suggestions?
Thanks,
Josh
---
Josh Anon
Studio Tools, Pixar Animation Studios
email@hidden
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.