Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6881715
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T05:09:52+00:00 2026-05-27T05:09:52+00:00

I have an array of NSMutableDictionary objects which are displayed in a master–detail interface

  • 0

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 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T05:09:53+00:00Added an answer on May 27, 2026 at 5:09 am

    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.


    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have An NSMutableArray of NSMutableDictionary Which Looks like this Object 1 of Array
I have an NSMutableDictionary, analyzedPxDictionary , containing a bunch of Pixel objects (a custom
I have an array of a few million numbers. double* const data = new
I have been trying to add an object as an NSMutableDictionary to my array,
I have my function getAllData, which is returning an array with dictionaries. - (NSArray
i have an array list of custom objects. each object contains a value i
I have array of select tag. <select id='uniqueID' name=status> <option value=1>Present</option> <option value=2>Absent</option> </select>
I have array like this: $path = array ( [0] => site\projects\terrace_and_balcony\mexico.jpg [1] =>
if i have array array[0] = jack; array[1] = jill; array[2] = lisa; array[2]
An array is defined of assumed elements like I have array like String[] strArray

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.