Search code examples
iospropertiesnsnotificationcenterkey-value-coding

Notification for property changes in NSObject


Is it possible to be notified for changes of all properties in an object? I would like to have a selector called whenever one of the properties in an NSObject is changed.

So far, I've only seen keyPathsForValuesAffectingValueForKey:, which isn't what I want, but it is persistent in showing up in my search results.

The specific objective that I currently have is to have a "FilterModel" that has properties for the specific filter characteristics. When any property is changed, I would like to update a UITableView with the newly filtered results.


Solution

  • You might be able to do that by querying the properties list of an object using Objective-C runtime and registering your custom class as an observer to them.

    #import <objc/runtime.h>
    
    
    //id yourObject;
    
    unsigned int count;
    objc_property_t* properties = class_copyPropertyList([yourObject class], &count);
    for (int i = 0; i < count; i++)
    {
        const char* propertyName = property_getName(properties[i]);
        NSString *stringPropertyName = [NSString  stringWithCString:propertyName encoding:NSUTF8StringEncoding];
        [yourObject addObserver:self forKeyPath:stringPropertyName options:NSKeyValueObservingOptionNew context:nil];
    }
    

    Also, don't forget to remove your custom class from the observer list before deallocation. Whenever a property changes, the called method is:

    - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context