user500
user500

Reputation: 4519

Binding pointers in Objective-C

At some point in my code I set UIImageView * imageView.image to UIImage * myImage. From this point I would love to view changes of myImage in imageView.

On any myImage change, I want to imageView to show myImage. Hope you understand. Thank you.

-- Edit 1 for better explanation.

At some point in code, i set imageView's image to myClass.image. And from this point I want to imageView react on any change of myClass.image. For example myClass.image = [UIImage imageNamed:@"foo"];. Both imageView and myClass.image are properties with retain. Now, when I change the myClass.image, I also have to set imageView.image = myClass.image to see new image in image view.

Upvotes: 0

Views: 168

Answers (2)

Richard J. Ross III
Richard J. Ross III

Reputation: 55543

I wrote a utility class for this a while back, and so you can download it here from my dropbox.

The syntax is like this:

[self bind:@"myImage" toObject:imageView keyPath:@"image"];
...
[self unbind:@"myImage" fromObject:imageView keyPath:@"image"];

Upvotes: 1

deanWombourne
deanWombourne

Reputation: 38475

Take a look at KVO.

Add an observer to the myClass.image property and when it changes, update your imageView. The code would look something like :

// To add the observer
[myClass addObserver:self forKeyPath:@"image" options:0 context:0];


// And to listen for changes
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:@"image"])
        myImageView.image = object.image;
    else
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}

Upvotes: 2

Related Questions