Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 834
AmitSri Avatar asked Jun 15 '11 07:06

AmitSri


People also ask

What is Property observation in Swift?

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.

What is Key-Value Coding and Key-Value observing?

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.

What is key-value observing?

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.

What does NSObject mean?

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.


1 Answers

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.

like image 180
Amy Worrall Avatar answered Sep 19 '22 14:09

Amy Worrall