Re: rewriting observed keyPath
Re: rewriting observed keyPath
- Subject: Re: rewriting observed keyPath
- From: Quincey Morris <email@hidden>
- Date: Tue, 15 Feb 2011 10:51:34 -0800
On Feb 15, 2011, at 05:11, Remco Poelstra wrote:
> I've a "PresetsController" which holds a dictionary containing preset settings for my application. The presets contain trees (Mutable Dictionaries) of keys.
> To save the GUI code from bothering with tracking the current preset, I want to give my PresetController the option to replace a keyPath like @"current.parameter.subparameter.value" to @"preset2.parameter.subparameter.value".
> I implemented it with a valueForUndefinedKey:
> - (id) valueForUndefinedKey:(NSString *)key {
> if ([key isEqual:@"current"])
> return [presets valueForKey:currentPreset]; //presets is a NSMutableDicitonary, currentPreset a NSString
> else
> return [presets valueForKey:key];
> }
>
> , returning the dictionary belonging to the current preset. This works for setting and reading using keyPaths. It does not work for observing a keyPath like @"current.parameter.subparameter.value". How should I implement that?
I think you're making this too hard. If you need to observe a key path that includes the "current" key, then just define a [derived] "current" property for the presets controller (assuming that's the class that has the above code). The getter would look like this:
- (NSDictionary*) current {
return [presets valueForKey:currentPreset];
}
The only thing you have to do is make sure that "current" is KVO compliant, which means that notifications need to be sent out whenever the underlying value changes:
[self willChangeValueForKey: @"current"];
currentPreset = ...
[self didChangeValueForKey: @"current"];
wherever you change the current preset. There are other possible variations, depending on what's most convenient with your class:
1. Obviously you could vary this by keeping a pointer to the current preset dictionary in an instance variable too.
2. If "currentPreset" is itself a KVO compliant property, you don't need to generate KVO notifications manually (the second code fragment). Instead, you'd use:
+ (NSSet*) keyPathsForValuesAffectingCurrent {
return [NSSet setWithObject: @"currentPreset"];
}
and write:
self.currentPreset = ...
_______________________________________________
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