KVO在NSCountedSet? [英] KVO on an NSCountedSet?

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

问题描述

我想监视一个NSCountedSet,看看它的内容是否改变。设置KVO似乎编译,但它没有被触发。第一个问题:你能观察一套吗?

I'd like to monitor an NSCountedSet to see if its contents changes. Setting up KVO seems to compile but it's not being triggered. First question: can you observe a set? If so then is there something wrong with this message?

    [subViewA addObserver:subViewB forKeyPath:@"countedSet" options:0 context:NULL];

我真的只是想监视计数

编辑 - 这里是观察者(subViewB):

Edit - here's the observer (subViewB):

- (void)observeValueForKeyPath:(NSString *)keyPath 
                      ofObject:(id)object 
                        change:(NSDictionary *)change 
                       context:(void *)context {
    if ([keyPath isEqual:@"countedSet"]) {
        NSLog(@"Set has changed");
    }
}

Edit2 addObserver消息从subView到viewController。所以我试图得到一个subView观察NSCountedSet在另一个viewController的subViews。键路径是相对于接收者 - 我假设是subViewA。

Edit2 - moved the addObserver message from the subView to the viewController. So I'm trying to get one subView to observe a NSCountedSet in another of the viewController's subViews. key path is "relative to the receiver" - which I assume to be subViewA.

推荐答案

直接与set对象交谈发出KVO更改通知。您需要以KVC兼容的方式更改属性的设置值。有两种方法:

Talking directly to the set object does not issue KVO change notifications. You need to make changes to the property's set value in a KVC-compliant way. There are two ways:


  1. 向属性所有者发送 mutableSetValueForKey:消息。这将给你一个假的设置对象,包装的属性,并发布KVO通知围绕你做的每一个更改。

  2. 实现集合访问器方法的属性,并使用它们无处不在。每个方法的实现直接涉及底层集合对象;所有不在这些方法之一的代码应该通过它们。因此,例如,要添加一个对象,你不应该使用 [myCountedSet addObject:foo] (除了 addCountedSetObject:);您应该使用 [self addCountedSetObject:foo]

  1. Send the property owner a mutableSetValueForKey: message. This will give you a fake set object that wraps the property and posts KVO notifications around each change you make to it.
  2. Implement the set accessor methods for the property, and use them everywhere. The implementation of each method talks directly to the underlying set object; all code that isn't in one of these methods should go through them. So, for example, to add an object, you should not use [myCountedSet addObject:foo] (except in addCountedSetObject:); you should use [self addCountedSetObject:foo] instead.

2。它可能听起来像更多的工作,但它不是很多,它使得真正好的代码。

I recommend #2. It may sound like more work, but it's not much, and it makes for really good code.

更多细节 (尽管这不是特定于Core Data)。

More details in the Model Object Implementation Guide and in the Core Data Programming Guide (even though this is not specific to Core Data).

这篇关于KVO在NSCountedSet?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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