LoginSignup
1
1

More than 5 years have passed since last update.

KVOで前回と値が異なる場合だけ処理を行う

Posted at

KVOを行う場合、前回と値が同じであれば処理をスキップしたいことがあります。
KVO自体には重複ガードを行う機構はないので、NSKeyValueObservingOptionNewとNSKeyValueObservingOptionOldを設定して一つ前の値も取得します。

[self addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];

observeValueForKeyPathでchange辞書の中にoldValue/newValueが含まれているのでこれを比較すればOKです。

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if([keyPath isEqualToString:@"contentSize"]) {
        CGSize oldValue = [[change valueForKey:NSKeyValueChangeOldKey] CGSizeValue];
        CGSize newValue = [[change valueForKey:NSKeyValueChangeNewKey] CGSizeValue];
        if (oldValue.height == newValue.height && oldValue.width == newValue.width) { return; }
        // do somethings
    }
}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1