How to observe a change in NSObject properties

I have a subclass of NSObject with 70 properties, I need to observe the changes in all of them without adding each property one by one using the following:

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

. Please let me know the easiest way to do this. Right now I need a solution for 10.5 and later.

+6
source share
1 answer

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

Or you could implement keyPathsForValuesAffectingValueForKey: in the class in question. Create a new key in the class, which we will use only to detect changes. Then follow the method described above, and if the string passed is equal to your new key, return a set containing the names of all seventy properties. Then you can simply do KVO on your new key, and you will receive a notification when something changes. By doing this in this way, you will not know which property has changed, just one of them has done.

This can help tell us why you need it, as there may be a better design template to use.

+10
source

Source: https://habr.com/ru/post/890581/


All Articles