Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Basic KVC/KVO Implementation
#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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment