Dies wird Key-Value Observing genannt. Jedes Objekt, das mit Schlüsselwertcodierung kompatibel ist, kann beobachtet werden, und dies schließt Objekte mit Eigenschaften ein. Lesen Sie this programming guide darüber, wie KVO funktioniert und wie Sie es verwenden. Hier ist ein kurzes Beispiel (Disclaimer: es könnte nicht funktionieren)
- (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
}
}
vergessen Sie nicht, Beobachter zu entfernen in '-dealloc', wie folgt aus:' [Imageview removeObserver: self forKeyPath: @ "Bild"]; ' –