2012-05-09 12 views
16

UIImageView.imageプロパティにオブザーバを設定する方法があるので、プロパティが変更されたときに通知を受け取ることができますか?おそらくNSNotification?これをどうやってやりますか?私のUIImageView.imageプロパティが変更されたときに通知を受ける方法はありますか?

私はUIImageViewsの数が多いので、どの変更が起こったのかも知る必要があります。

どうすればよいですか?ありがとう。

答えて

20

これは、Key-Value Observingと呼ばれます。 Key-Value Codingに準拠しているオブジェクトはすべて観察できます。これにはプロパティを持つオブジェクトが含まれます。 KVOの仕組みと使用方法については、this programming guideをお読みください。 `[ImageViewのremoveObserver:自己forKeyPath: "画像" @]

- (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''でオブザーバを削除することを忘れないでください:ここでは(それが動作しない場合があります免責事項)が短い例であり、 ' –

関連する問題