콘텐츠로 건너뛰기
Home » 키밸류 옵저빙이란 » Page 2

키밸류 옵저빙이란

다음 gist는 앞의 Foo, Bar 를 통합 옵저빙 예이다.


#import <Foundation/Foundation.h>
static void* theContext = &theContext;
/// KVC/KVO 호환 클래스.
@interface Foo: NSObject
@property (copy, nonatomic) NSString* moo;
-(void)doubleBar;
@end
@implementation Foo
– (NSString *)moo
{
if(!_moo) {
_moo = @"hello";
}
return _moo;
}
/// 문자열을 두번 반복하도록 확장하는 메소드.
/// 수동으로 KVO 호환이 되도록 한다.
-(void)doubleBar
{
[self willChangeValueForKey:@"bar"];
_moo = [NSString
stringWithFormat:@"%@%@", _moo, _moo];
[self didChangeValueForKey:@"bar"];
}
@end
/// 옵저버 클래스
@interface Bar: NSObject
@end
@implementation Bar
– (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
if(context == theContext) {
NSLog(@"the foo's bar has changed from:%@ to:%@",
[change objectForKey:NSKeyValueChangeOldKey],
[change objectForKey:NSKeyValueChangeNewKey]
);
} else {
[super observeValueForKeyPath:keyPath
ofObject:object
change:change
context:context
];
}
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here…
Foo* foo = [[Foo alloc] init];
NSLog(@"foo's bar is set for initial time.");
foo.moo = @"one";
Bar* x = [[Bar alloc] init];
[foo addObserver:x
forKeyPath:@"bar"
options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew
context:theContext];
foo.moo = @"two";
[foo doubleBar];
[foo removeObserver:x forKeyPath:@"bar"];
}
return 0;
}

view raw

main.m

hosted with ❤ by GitHub

Pages: 1 2 3
%d 블로거가 이것을 좋아합니다: