Is there a way to get notified when my UIImageView.image property changes?

cocoa-touch, ios, iphone, objective-c, xcode

Solution

This is called Key-Value Observing. Any object that is Key-Value Coding compliant can be observed, and this includes objects with properties. Have a read of this programming guide on how KVO works and how to use it. Here is a short example (disclaimer: it might not work)

- (id) init
{
    self = [super init];
    if (!self) return nil;

    // imageView is a UIImageView
    [imageView addObserver:self
                forKeyPath:@"image"
                   options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld
                   context:NULL];

    return self;
}

- (void) observeValueForKeyPath:(NSString *)path ofObject:(id) object change:(NSDictionary *) change context:(void *)context
{
    // this method is used for all observations, so you need to make sure
    // you are responding to the right one.
    if (object == imageView && [path isEqualToString:@"image"])
    {
        UIImage *newImage = [change objectForKey:NSKeyValueChangeNewKey];
        UIImage *oldImage = [change objectForKey:NSKeyValueChangeOldKey];

        // oldImage is the image *before* the property changed
        // newImage is the image *after* the property changed
    }
}

Problem

Is there a way to set an observer on a UIImageView.image property, so I can get notified of when the property has been changed? Perhaps with NSNotification? How would I go about doing this? I have a large number of UIImageViews, so I'll need to know which one the change occurred on as well. How do I do this? Thanks.

Original source