http://xserver.iteye.com/blog/1767830
http://blog.youkuaiyun.com/a6472953/article/details/7817538
http://www.cnblogs.com/pengyingh/articles/2383629.html
http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/KeyValueObserving/KeyValueObserving.html#//apple_ref/doc/uid/10000177i
- //注册监听
- [mTextView addObserver:self forKeyPath:@"text" options:NSKeyValueObservingOptionNew context:nil];
- //处理属性改变事件
- - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
- {
- UITextView *mTextView = object;
- NSLog("the textView content is change!!");
- }
-------------------------------
cocoa的KVO模型中,有两种通知观察者的方式,自动通知和手动通知。
自动通知由cocoa在属性值变化时自动通知观察者,
手动通知需要在值变化时调用 willChangeValueForKey:和didChangeValueForKey:
通知调用者。为求简便,我们一般使用自动通知。
要使用手动通知,需要在 automaticallyNotifiesObserversForKey方法中明确告诉cocoa,哪些键值要使用自动通知:
- //重新实现NSObject类中的automaticallyNotifiesObserversForKey:方法,返回yes表示自动通知。
- + (BOOL)automaticallyNotifiesObserversForKey:(NSString*)key
- {
- //当这两个值改变时,使用自动通知已注册过的观察者,观察者需要实现observeValueForKeyPath:ofObject:change:context:方法
- if ([key isEqualToString:@"isFinished"])
- {
- return NO;
- }
- return [super automaticallyNotifiesObserversForKey:key];
- }
- 手动通知在需要改变值_isFinished变量的地方,使用
- [self willChangeValueForKey:@"isFinished"];
- finished = YES;
- [self didChangeValueForKey:@"isFinished"];