I am writing a programme for Mac OS X, and came across the following problem:
In one of my classes there is a number of boolean properties, which are accessed using KVO (that is, by valueForKey:
and setValue:forKey:
methods. Their number is likely to grow.
Each time i set one of these properties, i need to change the date of the last modification, which is also a property. So i end up having to write a new setter for each new property.
What i would like to do instead is to override the setValue:forKey:
method so that it set the corresponding property and the date of the last modification, but i can't figure out how to do that without a) adding if
s to the setValue:forKey:
method (to check the name of the key and set the corresponding _variable
); and b) without falling into an infinite cycle.
Is there a way to do it? Or is it a bad idea altogether?
Both issues a) and b) can be solved by simply calling the implementation of the NSObject superclass in your overridden implementation:
There will be no infinite cycle because calling the super class will not result in any kind of recursion. Also, there is no need to call your setters or set your instance variables explicitly because the super class implementation will take care of this.