Search code examples
cocoapropertieskey-value-observingnsobject

How to observe change in NSObject properties


I have subclass of NSObject having 70 properties, i need to observe change in all of them without adding each property one-by-one using following :

[self addObserver: self
       forKeyPath: @"propertyname"
          options: NSKeyValueObservingOptionNew
          context: NULL];

. Please let me know the easiest way to do that. Right now,i need solution for 10.5 and later.


Solution

  • You could use the objective-C runtime function class_copyPropertyList() to get all the properties of that class, then loop through the list and use property_getName() to get something that should work with key value observing.

    Or you could implement keyPathsForValuesAffectingValueForKey: on the class in question. Make a new key on the class, that we're only going to use for change detection. Then implement the above method, and if the passed in string is equal to your new key, return a set containing the names of all seventy properties. Then you can just do KVO on your new key, and you'll get notified when anything changes. Doing it this way, you won't know which property changed, just that one of them did.

    It might help to tell us why you need to do this, as there might be a better design pattern to use.