Điều này được gọi là Quan sát giá trị khóa. Bất kỳ đối tượng nào tuân thủ Mã hóa giá trị khóa đều có thể được quan sát và điều này bao gồm các đối tượng có thuộc tính. Hãy đọc số this programming guide về cách thức hoạt động của KVO và cách sử dụng nó. Dưới đây là một ví dụ ngắn (từ chối trách nhiệm: nó có thể không hoạt động)
- (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
}
}
đừng quên để loại bỏ quan sát viên trong '-dealloc', như thế này:' [IMAGExem removeObserver: tự forKeyPath: @ "hình ảnh"]; ' –