KVO on an NSCountedSet?

I want to track an NSCountedSet to see if its contents are changing. KVO setup seems to be compiling but not starting up. First question: can you watch the set? If so, is there something wrong with this message?

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

I'm just trying to control the count (number of objects) in the set if that helps.

Edit - here is 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 - the addObserver message was moved from the sub-object to the viewController. Therefore, I am trying to get one subView to watch an NSCountedSet in another viewController submatrix. the "relative to the receiver" key path, which I suppose to be subViewA.

+4
source share
3 answers

Talking directly to a given object does not give a notification of a KVO change. You need to make changes to the value of the property set using the KVC-compatible method. There are two ways:

  • Send mutableSetValueForKey: message to the property owner. This will give you a fake given object that wraps the property and publishes KVO notifications around every change you make to it.
  • Implement access methods for this object and use them everywhere. The implementation of each method is directly related to the base given object; all code that is not in one of these methods must go through them. For example, to add an object, you should not use [myCountedSet addObject:foo] (except addCountedSetObject: ; you should use [self addCountedSetObject:foo] .

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

More details in the Guide for the implementation of the model object and in the master data Programming Guide (even if this does not apply to the master data).

+7
source

There are certain methods for manually changing KVOs for uncontrolled relationships between many.

Don't you want to set options to a non-zero value? For example, NSKeyValueObservingOptionNew

Also Mike Ash KVO Helper is pretty good.

In the NSSet docs on addObserver:

NSSet objects are not observed, so this method throws an exception when called on an NSSet object. Instead of observing a set, observe unordered to-many, for which a set is a set of related objects.

+3
source

Some things to check:

  • Is myController not nil ? If it is nil , the addObserver:::: message just silently crashes to the floor.
  • Is your method called at all? This may be called, but not with the key path that you expect. (I did not expect this either, but it is worth checking.)
0
source

All Articles