Inter-class Dependent Keys
Inter-class Dependent Keys
- Subject: Inter-class Dependent Keys
- From: Jonathon Mah <email@hidden>
- Date: Sat, 5 Mar 2005 22:48:58 +1030
For the KVO-inclinded:
While playing around with bindings in a little test app, I came across a case of a key in one class that is dependent on a key in another class. Specifically, the title of a button depends on whether the ArrayController canSelectNext. The documentation tells me that you can't use the
+[NSObject setKeys:triggersChangeNotificationsForDependentKey:] with different classes. (Documentation quote: "It’s common that the value of one property of a class is dependent on the value of another property of the
same class.", emphasis mine.) The title of the button is bound to the key '
myButtonTitle' in the controller class:
- (NSString *)myButtonTitle
{
if ([arrayController canSelectNext])
return @"Next";
else
return @"Add";
}
To trigger this change, I do this:
- (void)awakeFromNib
{
[arrayController addObserver:self forKeyPath:@"canSelectNext" options:NULL context:NULL];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if (object == arrayController && [keyPath isEqualToString:@"canSelectNext"])
{
[self willChangeValueForKey:@"myButtonTitle"];
[self didChangeValueForKey:@"myButtonTitle"];
}
}
The thing I don't like about this is the whole '
willChangeValueForKey:' '
didChangeValueForKey:' both being called after the value has already changed (screwing it up should something observing '
myButtonTitle' ever want to get the old value).
What is the correct way to handle this situation? I have a few thoughts, but they all involve more code than I feel should be necessary.
Jonathon Mah
email@hidden
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden