Search code examples
iossdwebimage

why use "willChangeValueForKey:" in SDWebImage?


There is a class named "SDWebImageDownloaderOperation" which has the following method in SDWebImageView lib.

- (void)setFinished:(BOOL)finished {
    [self willChangeValueForKey:@"isFinished"];
    _finished = finished;
    [self didChangeValueForKey:@"isFinished"];
}

however, rs does not override automaticallyNotifiesObserversForKey: and don't implement observeValueForKeyPath:ofObject:change:context: methods,so what is the purpose of writing

[self willChangeValueForKey:@"isFinished"]

and

 [self didChangeValueForKey:@"isFinished"]

Solution

  • The key reason here is that SDWebImageDownloaderOperation is a subclass of NSOperation and this class doesn't work with normal KVO notification like all the other classes. This operation performs some task on background, so you need to inform the operating system when your operation is finished and when is still running.

    Apple suggests here to explicitly call willChangeValueForKey and didChangeValueForKey.

    If you are looking for a better explanation why NSOPerations don't have normal KVO you can read this answer Why does NSOperation disable automatic key-value observing?