2012-05-09 12 views

Respuesta

20

Esto se llama Observación de valores-clave. Se puede observar cualquier objeto que sea compatible con Codificación de clave-valor, y esto incluye objetos con propiedades. Lea this programming guide sobre cómo funciona KVO y cómo usarlo. Aquí está un ejemplo corto (disclaimer: no podría funcionar)

- (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 
    } 
} 
+1

no se olvide de quitar observador en '-dealloc', así:' [imageView removeObserver: auto forKeyPath: @ "imagen"]; ' –

Cuestiones relacionadas