0

So I have two properties defined

@property (nonatomic) float continous;
@property (nonatomic, readonly) NSInteger discrete;

continous is an actual property that varies continously, while the getter for discrete looks like this:

- (NSInteger)discrete {
  return floor(continuous);
}

So, now I want to KVO on discrete, of course, I need to implement the following in my class:

+ (NSSet *)keyPathsForValuesAffectingDiscrete {
  return [NSSet setWithObject:NSStringFromSelector(continuous)];
}

Now, the problem is that since continuous is constantly changing, KVO would constantly send out updates, even though discrete has not actually changed! For example, KVO would keep updating me as continous varies from 0 to 0.9, but during this process, discrete is always 0. Now I don't really want that, is there anyway to only make KVO fire up changes when discrete has actually changed?

Enzo
  • 969
  • 1
  • 8
  • 23

1 Answers1

2

Rather than making a derived property for discrete, you could make it a stored property which is publicly readonly but privately readwrite. Implement the setter for continuous yourself, like so:

- (void) setContinuous:(float)newValue
{
    _continuous = newValue;
    NSInteger newDiscrete = floor(_continuous);
    if (newDiscrete != _discrete)
        self.discrete = newDiscrete;
}
Ken Thomases
  • 88,520
  • 7
  • 116
  • 154