Re: Inter-class Dependent Keys
Re: Inter-class Dependent Keys
- Subject: Re: Inter-class Dependent Keys
- From: Ricky Sharp <email@hidden>
- Date: Sat, 5 Mar 2005 08:13:36 -0600
On Mar 5, 2005, at 6:18 AM, Jonathon Mah wrote:
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.
Look into using setKeys:triggerChangeNotificationsForDependentKey:
A common example is one where your model has two properties: lastName
and firstName. Along with supplying accessors for those properties, it
also supplies a getter for a fullName (derived) property. Since
fullName depends on both lastName and firstName, you'd do this
(typically within your model's +initialize):
[self setKeys:[NSArray arrayWithObjects:@"lastName", @"firstName", nil]
triggerChangeNotificationsForDependentKey:@"fullName"];
___________________________________________________________
Ricky A. Sharp mailto:email@hidden
Instant Interactive(tm) http://www.instantinteractive.com
_______________________________________________
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