简体   繁体   English

Objective-C中的绑定指针

[英]Binding pointers in Objective-C

At some point in my code I set UIImageView * imageView.image to UIImage * myImage .在我的代码中的某个时刻,我将UIImageView * imageView.image设置为UIImage * myImage From this point I would love to view changes of myImage in imageView .从这一点来看,我很乐意在imageView中查看myImage的变化。

On any myImage change, I want to imageView to show myImage .在任何myImage更改时,我想imageView显示myImage Hope you understand.希望你能理解。 Thank you.谢谢你。

-- Edit 1 for better explanation. -- 编辑 1 以获得更好的解释。

At some point in code, i set imageView's image to myClass.image .在代码中的某个时刻,我将 imageView 的图像设置为myClass.image And from this point I want to imageView react on any change of myClass.image .从这一点开始,我想imageViewmyClass.image的任何变化做出反应。 For example myClass.image = [UIImage imageNamed:@"foo"];例如myClass.image = [UIImage imageNamed:@"foo"]; . . Both imageView and myClass.image are properties with retain. imageViewmyClass.image都是保留的属性。 Now, when I change the myClass.image , I also have to set imageView.image = myClass.image to see new image in image view.现在,当我更改myClass.image时,我还必须设置imageView.image = myClass.image才能在图像视图中看到新图像。

Take a look at KVO . 看看 KVO

Add an observer to the myClass.image property and when it changes, update your imageView .将观察者添加到myClass.image属性,当它发生变化时,更新您的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.我不久前为此编写了一个实用程序 class,因此您可以从我的保管箱中下载它。

The syntax is like this:语法是这样的:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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