I have an entity which is a subclass of NSManagedObject called Event. I have also registered a few modeled attributes of this entity for KVO change notifications:
[self.event addObserver:self
forKeyPath:@"numGuests"
options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld
context:&numGuestsContext];
[self.event addObserver:self
forKeyPath:@"checkedIn"
options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld
context:&checkedInContext];
[self.event addObserver:self
forKeyPath:@"seatedCount"
options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld
context:&seatedContext];
However it seems the observeValueForKeyPath method notification is getting triggered even though the value of NSKeyValueChangeOldKey and NSKeyValueChangeNewKey in the change dictionary are equal???
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
NSNumber *oldValue = [change valueForKey:NSKeyValueChangeOldKey];
NSNumber *newValue = [change valueForKey:NSKeyValueChangeNewKey];
if ([oldValue isEqualToNumber:newValue])
{
return;
}
For now i have resorted to just doing a quick sanity check to see if they are equal but i would like to understand why this notification is getting fired to begin with?
UPDATE: @jszumski mentioned in the comments that this most likely is happening because the objects are different although logically equal. The Event entity object always has the same address however the object i am observing, which is an attribute within the entity, keeps changing addresses although i am not sure why??
I am wondering if accessing this value in a bg query thread could cause Core Data to create new internal objects within the entity with the same value?
Simply, you are assuming the functionality of the NSKeyValueObservingOptions
. They do not work as you are expecting them to. The flags you send only decide what the contents of the change dictionary are. The observer is always triggered whenever the setters are called.
Besides, when you are sending flags old and new, that really just says "I would like the old value, and new value. I don't care if they are equal or not".
Please read the reference to learn more:
NSKeyValueObservingOptions
These constants are passed to addObserver:forKeyPath:options:context: and determine the values that are returned as part of the change dictionary passed to an observeValueForKeyPath:ofObject:change:context:. You can pass 0 if you require no change dictionary values.
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