KVO: how to call setValue... inside setValue and not get into infinite loop?

1.3k views Asked by At

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 ifs 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?

1

There are 1 answers

3
hverlind On BEST ANSWER

Both issues a) and b) can be solved by simply calling the implementation of the NSObject superclass in your overridden implementation:

- (void)setValue:(id)value forKey:(NSString *)key
{
    _lastModificationDate = [NSDate date];
    [super setValue:value forKey:key];
}

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.