简体   繁体   中英

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.

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];
}

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"];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM