Search code examples
objective-ckey-value-observingkey-value-coding

Simple setter in objc still generates change value notification


I have simple setter like

- (void) setValue: (int) newVal
{
    value = newVal;
}

where value is int value; instance variable.

How is it possible that using [myobj setValue: 10]; still generates notification for observers, even though my setter doesn't do any notification explicitely (i.e. it doesn't call willChangeValueForKey nor didChangeValueForKey).

Not sure if it's relevant or not, but I'm using plain old Mac OS X. Is this different on iOS?


Solution

  • Cocoa (and CocoaTouch) use a technique called "isa-swizzling" for automatic KVO support.

    It works by dynamically subclassing the class of the observed object, overriding the setter of the observed property. The implementation of the overridden method sends the willChangeValueForKey: and didChangeValueForKey: messages (and, of course calls the original implementation in between).

    When observation for an object is set up the object's original isa pointer (pointing to the class of the object) is replaced by the new dynamically created subclass. Since the subclass does not add to the object's size this is possible without harming the memory layout.