2012-05-09 11 views

risposta

20

Questo viene chiamato Osservazione valore-chiave. È possibile osservare qualsiasi oggetto conforme alla codifica Key-Value e questo include oggetti con proprietà. Leggi il this programming guide su come funziona KVO e come usarlo. Ecco un breve esempio (disclaimer: non potrebbe funzionare)

- (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

non dimenticare di rimuovere osservatore '-dealloc', in questo modo:' [IMAGEVIEW removeObserver: auto forKeyPath: @ "immagine"]; ' –

Problemi correlati