2012-05-09 63 views

回答

20

這被稱爲鍵值觀測。任何符合鍵值編碼的對象都可以被觀察到,並且這包括具有屬性的對象。請閱讀this programming guide瞭解KVO如何工作以及如何使用它。下面是一個簡單的例子(免責聲明:可能無法正常工作)

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

別忘了在'刪除觀察者-dealloc',像這樣:'[ImageView的removeObserver:自forKeyPath:@ 「形象」];' –

相關問題