[Objective-C Tip] Key-Value Observing
개발을 하다보면, 변경사항을 통보받을때, 감시객체를 등록하면, 편리합니다.
감시객체를 등록하고, 동작이 일어나는 부분에서 변경을 해주면, 변경된 결과를 바로 받아볼수 있습니다.
1. 감시객체 등록
[obj addObserver:selfforKeyPath:@"enable"options:NSKeyValueObservingOptionNew| NSKeyValueObservingOptionOld context:NULL];
______________________________________________________________________________________________________________________
2. 감시객체 변경
- (IBAction)observer:(id)sender
{
UIButton *temp = (UIButton*)sender;
if (temp.tag==0)
{
NSLog(@"YES");
temp.tag=1;
[objsetValue:[NSNumbernumberWithBool:YES] forKey:@"enable"];
}
else
{
NSLog(@"NO");
temp.tag=0;
[objsetValue:[NSNumbernumberWithBool:NO] forKey:@"enable"];
}
// obj.enable=YES;
}
______________________________________________________________________________________________________________________
3. 감기객체가 변경되면 알려줌
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if([keyPath isEqualToString:@"enable"])
{
for(NSString *val in [change allKeys])
{
NSLog(@"%@ : %@",val, [change objectForKey:val]);
}
BOOL newState=[[change valueForKey:NSKeyValueChangeNewKey] boolValue];
if (newState)
{
NSLog(@"YES");
}
else
{
NSLog(@"NO");
}
}
}
감시객체를 등록하고, 동작이 일어나는 부분에서 변경을 해주면, 변경된 결과를 바로 받아볼수 있습니다.
1. 감시객체 등록
[obj addObserver:selfforKeyPath:@"enable"options:NSKeyValueObservingOptionNew| NSKeyValueObservingOptionOld context:NULL];
______________________________________________________________________________________________________________________
2. 감시객체 변경
- (IBAction)observer:(id)sender
{
UIButton *temp = (UIButton*)sender;
if (temp.tag==0)
{
NSLog(@"YES");
temp.tag=1;
[objsetValue:[NSNumbernumberWithBool:YES] forKey:@"enable"];
}
else
{
NSLog(@"NO");
temp.tag=0;
[objsetValue:[NSNumbernumberWithBool:NO] forKey:@"enable"];
}
// obj.enable=YES;
}
______________________________________________________________________________________________________________________
3. 감기객체가 변경되면 알려줌
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if([keyPath isEqualToString:@"enable"])
{
for(NSString *val in [change allKeys])
{
NSLog(@"%@ : %@",val, [change objectForKey:val]);
}
BOOL newState=[[change valueForKey:NSKeyValueChangeNewKey] boolValue];
if (newState)
{
NSLog(@"YES");
}
else
{
NSLog(@"NO");
}
}
}
댓글
댓글 쓰기