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.
Property observers observe and respond to changes in a property's value. Property observers are called every time a property's value is set, even if the new value is the same as the property's current value. You can add property observers in the following places: Stored properties that you define.
KVO and KVC or Key-Value Observing and Key-Value Coding are mechanisms originally built and provided by Objective-C that allows us to locate and interact with the underlying properties of a class that inherits NSObject at runtime.
Key-value observing is a mechanism that enables an object to be notified directly when a property of another object changes. It is a mode of communication between objects in applications designed in conformance with the Model-View-Controller design pattern.
The root class of most Objective-C class hierarchies, from which subclasses inherit a basic interface to the runtime system and the ability to behave as Objective-C objects.
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.
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