4
votes

I have an array of NSMutableDictionary objects which are displayed in a master–detail interface which has a few text fields and a bunch of check boxes. The controls are bound to the dictionary keys, accessed through an array controller's selection.

I'd like to add some logic which clears one check box when another is cleared, and restores the original value if it's rechecked in the same session. Since I need to associate storage with the dictionary, and need to add code too, I thought I'd use composition to extend NSMutableDictionary.

Here's what I've done:

  1. I created a LibraryEntry subclass which contains an NSMutableDictionary.
  2. I implemented forwardInvocation:, respondsToSelector:, methodSignatureForSelector:, and after some trial-and-error valueForUndefinedKey:.
  3. I created my forwarder objects.
  4. I left the bindings as they were.

It loads up the data just fine, but I'm guessing that KVO won't work correctly. I'm guessing the binder is calling addObserver: on the my object but I haven't implemented anything special to handle it.

I thought of simply overriding addObserver: and forwarding the message to the dictionary. But if I do that the observeValueForKey: notifications won't originate from my object (the original receiver of addObserver), but from the dictionary.

Before I tried to implement more transparent forwarding for these KVO calls, I thought ... this is getting messy. I keep reading "use composition, not subclassing" to get behavior like this. Is it just the wrong pattern for this situation? Why? Because of KVO?

It seems like I'd have cleaner results if I abandon composition and choose one of these alternatives:

  1. Use decorators, with one instance observing each dictionary
  2. Store the transient keys in the dictionary and have the controller remove them before saving
  3. Dispense with the dictionary and declare properties instead

Here's my code, in case it's helpful (values is the dictionary):

- (void)forwardInvocation:(NSInvocation *)anInvocation {
    if ([values respondsToSelector:[anInvocation selector]])
        [anInvocation invokeWithTarget:values];
    else
        [super forwardInvocation:anInvocation];
}

- (BOOL)respondsToSelector:(SEL)aSelector {
    if ( [super respondsToSelector:aSelector] )
        return YES;
    else
        return [values respondsToSelector:aSelector];
}

- (NSMethodSignature*)methodSignatureForSelector:(SEL)selector {
    NSMethodSignature* signature = [super methodSignatureForSelector:selector];
    if (!signature) signature = [values methodSignatureForSelector:selector];
    return signature;
}

-(id)valueForUndefinedKey:(NSString *)key {
    return [values valueForKey:key];
}
1

1 Answers

1
votes

I think with a combination of Objective-C associated storage, and some blocks, you could hook up arbitrary behaviors to a dictionary (or any other KVO compliant object) and solve your problem that way. I cooked up the following idea that implements a generic KVO-triggers-block mechanism and coded up and example that appears to do the sort of thing you want it to do, and does not involve subclassing or decorating foundation collections.

First the public interface of this mechanism:

typedef void (^KBBehavior)(id object, NSString* keyPath, id oldValue, id newValue, id userInfo);

@interface NSObject (KBKVOBehaviorObserver)

- (void)addBehavior: (KBBehavior)block forKeyPath: (NSString*)keyPath options: (NSKeyValueObservingOptions)options userInfo: (id)userInfo;
- (void)removeBehaviorForKeyPath: (NSString*)keyPath;

@end

This will allow you to attach block-based observations/behaviors to arbitrary objects. The task you describe with the checkboxes might look something like this:

- (void)testBehaviors
{
    NSMutableDictionary* myModelDictionary = [NSMutableDictionary dictionary];

    KBBehavior behaviorBlock = ^(id object, NSString* keyPath, id oldValue, id newValue, id userInfo) 
    {
        NSMutableDictionary* modelDictionary = (NSMutableDictionary*)object;
        NSMutableDictionary* previousValues = (NSMutableDictionary*)userInfo;

        if (nil == newValue || (![newValue boolValue]))
        {
            // If the master is turning off, turn off the slave, but make a note of the previous value
            id previousValue = [modelDictionary objectForKey: @"slaveCheckbox"];

            if (previousValue)
                [previousValues setObject: previousValue forKey: @"slaveCheckbox"];
            else
                [previousValues removeObjectForKey: @"slaveCheckbox"];

            [modelDictionary setObject: newValue forKey: @"slaveCheckbox"];
        }
        else
        {
            // if the master is turning ON, restore the previous value of the slave
            id prevValue = [previousValues objectForKey: @"slaveCheckbox"];

            if (prevValue)
                [modelDictionary setObject:prevValue forKey: @"slaveCheckbox"];
            else
                [modelDictionary removeObjectForKey: @"slaveCheckbox"];
        }
    };

    // Set the state...
    [myModelDictionary setObject: [NSNumber numberWithBool: YES] forKey: @"slaveCheckbox"];
    [myModelDictionary setObject: [NSNumber numberWithBool: YES] forKey: @"masterCheckbox"];

    // Add behavior
    [myModelDictionary addBehavior: behaviorBlock forKeyPath: @"masterCheckbox" options: NSKeyValueObservingOptionNew userInfo: [NSMutableDictionary dictionary]];

    // turn off the master
    [myModelDictionary setObject: [NSNumber numberWithBool: NO] forKey: @"masterCheckbox"];

    // we now expect the slave to be off...
    NSLog(@"slaveCheckbox value: %@", [myModelDictionary objectForKey: @"slaveCheckbox"]);

    // turn the master back on...
    [myModelDictionary setObject: [NSNumber numberWithBool: YES] forKey: @"masterCheckbox"];

    // now we expect the slave to be back on, since that was it's previous value
    NSLog(@"slaveCheckbox value: %@", [myModelDictionary objectForKey: @"slaveCheckbox"]);


}

I implemented the block/KVO hook-up by creating an object to keep track of the blocks and userInfos, then have that be the KVO observer. Here's what I did:

#import <objc/runtime.h>

static void* kKVOBehaviorsKey = &kKVOBehaviorsKey;    

@interface KBKVOBehaviorObserver : NSObject
{
    NSMutableDictionary* mBehaviorsByKey;
    NSMutableDictionary* mUserInfosByKey;
}
@end

@implementation KBKVOBehaviorObserver

- (id)init
{
    if (self = [super init])
    {
        mBehaviorsByKey = [[NSMutableDictionary alloc] init];
        mUserInfosByKey = [[NSMutableDictionary alloc] init];
    }
    return self;
}

- (void)dealloc
{
    [mBehaviorsByKey release];
    mBehaviorsByKey = nil;

    [mUserInfosByKey release];
    mUserInfosByKey = nil;

    [super dealloc];
}

- (void)addBehavior: (KBBehavior)block forKeyPath: (NSString*)keyPath userInfo: (id)userInfo
{
    @synchronized(self)
    {
        id copiedBlock = [[block copy] autorelease];
        [mBehaviorsByKey setObject: copiedBlock forKey: keyPath];
        [mUserInfosByKey setObject: userInfo forKey: keyPath];
    }
}

- (void)removeBehaviorForKeyPath: (NSString*)keyPath
{
    @synchronized(self)
    {
        [mUserInfosByKey removeObjectForKey: keyPath];
        [mBehaviorsByKey removeObjectForKey: keyPath];
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if (context == kKVOBehaviorsKey)
    {
        KBBehavior behavior = nil;
        id userInfo = nil;

        @synchronized(self)
        {
            behavior = [[[mBehaviorsByKey objectForKey: keyPath] retain] autorelease];
            userInfo = [[[mUserInfosByKey objectForKey: keyPath] retain] autorelease];
        }

        if (behavior) 
        {
            id oldValue = [change objectForKey: NSKeyValueChangeOldKey];
            id newValue = [change objectForKey: NSKeyValueChangeNewKey];
            behavior(object, keyPath, oldValue, newValue, userInfo);
        }
    }
}

@end

@implementation NSObject (KBKVOBehaviorObserver)

- (void)addBehavior: (KBBehavior)block forKeyPath: (NSString*)keyPath options: (NSKeyValueObservingOptions)options userInfo: (id)userInfo
{
    KBKVOBehaviorObserver* obs = nil;

    @synchronized(self)
    {
        obs = objc_getAssociatedObject(self, kKVOBehaviorsKey);
        if (nil == obs)
        {
            obs = [[[KBKVOBehaviorObserver alloc] init] autorelease];    
            objc_setAssociatedObject(self, kKVOBehaviorsKey, obs, OBJC_ASSOCIATION_RETAIN);
        }
    }

    // Put the behavior and userInfos into stuff...
    [obs addBehavior: block forKeyPath: keyPath userInfo: userInfo];

    // add the observation    
    [self addObserver: obs forKeyPath: keyPath options: options context: kKVOBehaviorsKey];
}

- (void)removeBehaviorForKeyPath: (NSString*)keyPath
{
    KBKVOBehaviorObserver* obs = nil;

    obs = [[objc_getAssociatedObject(self, kKVOBehaviorsKey) retain] autorelease];    

    // Remove the observation
    [self removeObserver: obs forKeyPath: keyPath context: kKVOBehaviorsKey];

    // remove the behavior
    [obs removeBehaviorForKeyPath: keyPath];
}

@end

One thing that's sort of unfortunate, is that you have to remove the observations/behaviors in order to break down the transitive retain cycle between the original dictionary and the observing object, so if you don't remove the behaviors, you'll leak the collection. But overall this pattern should be useful.

Hope this helps.