views:

755

answers:

3

Is it possible to observe (subscribe to) changes to values stored under different keys in an NSMutableDictionary? In my case the keys would already exist when the subscription is initiated, but the values change and I would like to be notified in this case. I would like the key of the changed value in the notification.

I assume that if my dictionary keys were all NSString instances I could just subscribe to each key path individually. But what if my keys are non-strings? Am I out of luck in that case?

+3  A: 

That's an interesting idea. I can't find anything in NSDictionary or NSDictionaryController that looks promising. My first instinct would be to use composition around an NSMutableDictionary and intercept calls to setObject:forKey: (and maybe -removeObjectForKey:) to notify subscribers of changes.

There's a Cocoa With Love post on subclassing NSMutableDictionary that will likely be useful should you choose to go that route. I also have created my own NSMutableDictionary subclasses, and you're welcome to use the open-source code.

You could design an observer protocol that could specify particular keys that should be monitored. Shouldn't be too much code, but more than I have time to throw down at the moment.

Quinn Taylor
Thanks. I think composition around an NSMutableDictionary is the way to go. I still can't see how to make that work unless the keys are NSStrings, but I think I can probably work with that.
Stig Brautaset
+2  A: 

I've successfully implemented this now, using composition around the NSMutableDictionary. I'm surprised how little code it took. The class I implemented is Board, used to represent the model in a board game. Anyone can subscribe to changes for board states by calling the addObserver: method, implemented like this:

- (void)addObserver:(id)observer {
    for (id key in grid)
        [self addObserver:observer
               forKeyPath:[key description]
                  options:0
                  context:key];
}

Since you can only subscribe to keys using the KVO model, I cheated and subscribed to the description of the key, but passing the key itself as the context. In objects that observe instances of my Board I implement the -observeValueForKeyPath:ofObject:change:context: to ignore the keyPath string and just use the passed-in context.

My simple Board class is not KVO compliant for the artificial properties I create using this method, so I passed 0 in the options property so the KVO machinery will not try to get the old/new values of those keys. That would cause my code to blow up.

Anything that changes the board (in my simple class there is only one method that does this) raise the necessary notifications to cause the KVO machinery to leap into action:

- (void)setPiece:(id)piece atLocation:(Location*)loc {
    [self willChangeValueForKey:[loc description]];
    [grid setObject:piece forKey:loc];
    [self didChangeValueForKey:[loc description]];
}

Voila! Subscription to an NSMutableDictionary with non-string keys!

Stig Brautaset
A: 

What about

[self setStateDictionary:[self stateDictionary]];

?

awolf
Voted down because I don't understand this answer relates to my question at all.
Stig Brautaset
This would trigger a change on the entire dictionary. An observer could then check whichever keys it may be interested in. For instance, if you are using this to update a user interface all you really need to know is 1) the UI needs to be re-drawn and 2) the parameters to use while doing so.
awolf
I see what you mean now. However, the point was to get notification about which individual keys changed. Each key is a grid location in my Board, so when a grid cell is updated I want to animate that. With your scheme I would have to keep a copy of the board in the View, and compare it with the current view when such a notification appears.
Stig Brautaset
I would have implemented your board a little differently: The board has a render function which takes a state object (represented by a NSDictionary). When a move is performed the "move-handler" updates the state and the updated state is passed back to the board for re-rendering. This keeps the code super clean but also has the advantage of being able to easily serialize and restore the state when the user exits/re-enters the App (NSDictionary implements the NSCoding protocol).
awolf