[Objective-C] kvo(key value observing)
1. kvo(key value observing)
해당 key의 value가 변할 때 통보받을 수 있는 방법
2. 샘플 코드
@interface People : NSObject
@property (retain, nonatomic) NSString* name;
@property (retain, nonatomic) NSString* addr;
@end
@implementation People
//@synthesize name,addr;
@end
@interface Car : NSObject
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context;
@end
@implementation Car
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
NSString* newValue = [change objectForKey:NSKeyValueChangeNewKey];
NSLog(@"%@",newValue);
NSLog(@"merong");
}
@end
int main()
{
People* p1 = [[People alloc] init];
// kvo 객체의 프라퍼티가 변할 때 통보 받을 수 있는 문법
Car* c1 = [[Car alloc] init];
[p1 addObserver:c1 forKeyPath:@"name" options:NSKeyValueObservingOptionNew context:nil];
p1.name=@"kim";
[p1 removeObserver:c1 forKeyPath:@"name"];
[p1 release];
[c1 release];
return 0;
}