Objective-C:向 NSMutableDictionary 添加一个观察者,当计数达到 0 时该观察者会收到通知
当 NSMutableDictionary 的计数达到 0 时,我希望收到通知。是否可以在不扩展 NSMutableDictionary 的情况下实现这一点(我听说你不应该这样做)?
例如,我是否可以有一个类别,通过调用原始方法同时检查 count 是否为 0 来模仿删除方法?或者有没有更简单的方法。我尝试了 KVO,但是没有用...
任何帮助都是值得赞赏的。
约瑟夫
I would like to be notified, when an NSMutableDictionary's count reaches 0. Is that possible without extending NSMutableDictionary (which I heard you should not really do)?
Could I e.g. have a category that mimicks remove methods by calling the original ones while checking whether count is 0? Or is there maybe a simpler way. I tried KVO, but that did not work...
Any help is appreciated.
Joseph
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当使用字典和其他“类簇”对象时,对它们进行“子类化”的最简单方法是创建一个子类并将其包装在相同类型的现有对象周围:
When working with Dictionaries and other "class cluster" objects, the easiest way to "subclass" them is to create a subclass and wrap it around an existing object of the same type:
我尝试使用我的第一个类别,这似乎有效:
NSMutableDictionary+NotifyOnEmpty.h
NSMutableDictionary+NotifyOnEmpty.m
不知道这是否是一个优雅的解决方案,但它似乎工作正常。
I tried with my first ever category, which seems to work:
NSMutableDictionary+NotifiesOnEmpty.h
NSMutableDictionary+NotifiesOnEmpty.m
Don't know if that is an elegant solution, but it seems to work okay.