观察NSMutableDictionary的更改 [英] Observing NSMutableDictionary changes

查看:107
本文介绍了观察NSMutableDictionary的更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以观察(订阅)NSMutableDictionary中不同键下存储的值的更改?在我的情况下,启动订阅时键已经存在,但是值会更改,在这种情况下,我希望得到通知.我想要通知中更改值的键.

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.

我假设,如果我的字典键都是NSString实例,那么我可以单独订阅每个键路径.但是,如果我的密钥是非字符串怎么办?在那种情况下我会走运吗?

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?

推荐答案

这是一个有趣的想法.我在NSDictionary或NSDictionaryController中找不到任何有前途的东西.我的第一个直觉是在NSMutableDictionary周围使用合成,并拦截对setObject:forKey:(可能还有-removeObjectForKey :)的调用,以将更改通知订户.

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.

关于将NSMutableDictionary细分为子类的内容,有一个可可与爱的帖子如果您选择走那条路线很有用.我也有创建了自己的NSMutableDictionary子类,欢迎您使用开源代码.

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.

这篇关于观察NSMutableDictionary的更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆