objective-cnsmutabledictionary

Observing NSMutableDictionary changes


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?


Solution

  • 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.