KVO键值观察机制,就是MVC中Model变化的时候通知View更新,使用该机制避免了胶水代码,即在任何数据更新的地方都得写更新UI的更新代码。具体系统系统:NSObject,NSArray,NSSet三种KVO机制,API如下@interface NSObject(NSKeyValueObserverRegistration)
- (void)addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context;
- (void)removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath;
@end
@interface NSArray(NSKeyValueObserverRegistration)
- (void)addObserver:(NSObject *)observer toObjectsAtIndexes:(NSIndexSet *)indexes forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context;
- (void)removeObserver:(NSObject *)observer fromObjectsAtIndexes:(NSIndexSet *)indexes forKeyPath:(NSString *)keyPath;
- (void)addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context;
- (void)removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath;
@end
@interface NSSet(NSKeyValueObserverRegistration)
- (void)addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context NS_AVAILABLE(10_4, 2_0);
- (void)removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath NS_AVAILABLE(10_4, 2_0);
@end
只解释@interfaceNSObject(NSKeyValueObserverRegistration)
- (void)addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context;
例如:
Class Model:NSObject
{
NSString *text;
}
Class Controller:NSObject
{
Model *model;
}
此时如果在Controller中想使用KVO机制得如下操作
[model addObserver:self forKeyPath:@“text” options:NSKeyValueObservingOptionNew context:nil];
这条语句意思是:当model的text属性变化时通知self,其中NSKeyValueObservingOptionNew 可以变换,context参数是void*类型,因此可以传递自己想传递的任何类型。
除此在Controller中还得实现
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
text属性变化时系统会回调这个函数,因此在这个函数中更新UI。
- (void)removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath;
删除观察者记得在释放本对象之前一定要remove observer,比如在dealloc中remove observer。
- (void)addObserver:(NSObject *)observer toObjectsAtIndexes:(NSIndexSet *)indexes forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context;
向数组中某个对象集合添加观察者