键值观察NSMutableSet [英] Key-Value Observing an NSMutableSet

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

问题描述

在一个普通类中,我有一个NSMutableSet属性.每当将对象添加到集合中或从集合中删除时,我都想执行一些自定义代码.我知道我可以为该类编写一些addObjectToSet:类似的方法,但是我想知道在集合上是否存在直接KVO的更优雅的解决方案.

In a plain class I have a NSMutableSet property. Whenever objects are added to or removed from the set, I want to perform some custom code. I know I could write a few addObjectToSet:-like methods to the class, but I was wondering if there's a more elegant solution with direct KVO on the set.

事实证明,当您尝试向其添加观察者时,NSSet将引发异常.毫不奇怪,因为可能没有观察到的命名keyPath.

As it turns out, NSSet will raise an exception when you try to add an observer to it. Not surprisingly, for there's probably no named keyPath to observe. The documentation is pretty clear about the exception, but I don't understand the suggested workaround:

而不是观察集合,而是观察集合是相关对象集合的无序对多关系.

Instead of observing a set, observe the unordered to-many relationship for which the set is the collection of related objects.

有人可以重申这是什么意思吗?那么解决方法将是什么样的?

Could someone reiterate what this means? And what a workaround would then look like?

推荐答案

这是一种非常密集的说法:不要在集合本身中添加观察者,在包含集合的类中添加观察者":

That's a pretty dense way of saying "don't add an observer to the set itself, add an observer to the class that contains the set":

[myObjWithASetAsIvar addObserver:self
                      forKeyPath:@"nameOfIvarHoldingTheSet"
                         options:NSKeyValueObservingOptionNew
                         context:nil];

一个棘手的问题是,您需要包装对集合的所有访问权限,以便发送正确的通知.在包含集合的类中:

The one tricky bit is that you need to wrap all your accesses to the set in order for the proper notifications to be sent. In the class containing the set:

[self willChangeValueForKey:@"nameOfIvarHoldingTheSet"];
// Do something with the set
[self didChangeValueForKey:@"nameOfIvarHoldingTheSet"];

还有两种专门用于集合的通知方法:

There are also two notification methods specifically for sets: willChangeValueForKey:withSetMutation:usingObjects: and didChangeValueForKey:withSetMutation:usingObjects:; you may find that they work better for you than the generic "value change" methods.

所有这些,我相信您在第一段中提到的解决方案以及彼得·霍西(Peter Hosey)在与吉里什(Girish)相关的问题中概述的方法,可能是最好的选择.

All that said, I believe that the solution you mentioned in your first paragraph, and outlined by Peter Hosey in the question Girish linked to, is probably the best way to go.

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

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