Search code examples
ioscocoakey-value-observing

KVO firing when value assigned is not different


If I have a property as follows

@property(assign, nonatomic) NSUInteger myValue;

And assign a property to it

self.myValue = 2;

KVO will fire as expected. If, later on, I then assign the same value to it

self.myValue = 2;

KVO will fire again. I had presumed that KVO in Objective-C would not fire if the value being assigned was not different. It appears that I am incorrect.

Is there a way to force this default behaviour, i.e. disable the KVO notifications firing every time a value is assigned? I can create my own accessors, but this could be quite a lot of work if there are a lot of properties that I want to change...

Thanks for any replies.


Solution

  • KVO fires when a setter (or other mutator) is called. There is no additional check. In general, KVO is extremely lightweight and performance sensitive. Since unnecessary changes are typically rare and in most cases harmless to the observer, they do not include the extra overhead of checking the old value. Checking the previous value could be expensive, for instance if a managed object hadn't been faulted, so doing a lot of work just to check for this case is not a default behavior.

    If you need to check how the value changed or didn't, you can do so as the observer by passing the options NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld. You will then receive both the new and old values and you can decide whether to do anything with that information. I've found in practice that this shouldn't be needed very often, however.