1

Whenever a property on my object is changed or updated I want to change a variable (nonce variable). This nonce is time-based. So everytime a property is updated this nonce gets updated to the current time.

Is there any way to automatically listen for all key changes on my object? Or will I have to manually maintain all keyvalue observers for each property separately?

Many thanks

Thomas Clayson
  • 29,657
  • 26
  • 147
  • 224
  • possible duplicate of [Key Value Observing - how to observe all the properties of an object?](http://stackoverflow.com/questions/13491454/key-value-observing-how-to-observe-all-the-properties-of-an-object) – Caleb May 14 '13 at 15:39

2 Answers2

6

Did you take a look at the Obj-C runtime functions? See here in the docs. For example, this gives you a list of all the properties in a class Lender. (BTW: I'm not at my Mac, so this is just straight out of the docs):

@interface Lender : NSObject {
    float alone;
}
@property float alone;
@end

you can get the list of properties using:

id LenderClass = objc_getClass("Lender");
unsigned int outCount;
objc_property_t *properties = class_copyPropertyList(LenderClass, &outCount);

you can then get the name of a property:

const char *property_getName(objc_property_t property)

If you pipe those names back into addObserver:forKeyPath:options:context you should be golden.

Maarten
  • 1,873
  • 1
  • 13
  • 16
1

Some ideas:

1) you can ask the runtime for the properties and ivars, and their types, and use that information to create and take down observers. Obviously a lot of work if you are doing this for one object.

2) if your properties are "regular", meaning all strong objects, then you can use @dynamic (to prevent setter/getter creation), then use resolveInstanceMethod: or other funky methods from NSObject to catch setMyObject: and myObject calls. You could in essence do what the system does for 'set...' calls, and dynamically get the string of the variable. You could then update/get an ivar, maybe one that has a prefix of "-" or something, and you'd be able to do what your observers would be doing.

3) You could put all the ivars in a "Helper" class, and direct all the setters to it (which could of course message you back), using forwardingTargetForSelector:. I'm using this technique (sort of) in one of my github projects

David H
  • 40,852
  • 12
  • 92
  • 138