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 (Cocoa-dev@lists.apple.com)

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:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to