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];
I'm really just trying to monitor the count of (number of objects in) the set if that helps.
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 - 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.
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:
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.[myCountedSet addObject:foo]
(except in addCountedSetObject:
); you should use [self addCountedSetObject:foo]
instead.I recommend #2. It may sound like more work, but it's not much, and it makes for really good code.
More details in the Model Object Implementation Guide and in the Core Data Programming Guide (even though this is not specific to Core Data).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With