1、KVO介绍
KVO机制NSKeyValueObserving协议支持,NS遵循了这个协议 ,所以NSObject的子类都可使用协议中的方法,下面方法可以注册监听
添加监听器
addObserver: forKeyPath: options: context:
删除监听
removeObserver: forKeyPath:
//重写下面的方法,当数据发生变化的时候会回调这个函数
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
2、测试代码
FKItemView.h
#ifndef FKItemView_h
#define FKItemView_h
#import <Foundation/Foundation.h>
#import "FKItem.h"@interface FKItemView : NSObject
@property (nonatomic, weak) FKItem *item;
-(void)showItemInfo;
@end#endif /* FKItemView_h */
FKItemView.m
#import <Foundation/Foundation.h>
#import "FKItemView.h"@implementation FKItemView
@synthesize item = _item;-(void)showItemInfo
{NSLog(@"item物品名为:%@,物品价格为:%d", self.item.name, self.item.price);
}
//自定义设置item
-(void)setItem:(FKItem *)item
{self->_item = item;
// self.item = item;//为item添加监听器,监听item的name属性的改变[self.item addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew context:nil];[self.item addObserver:self forKeyPath:@"price" options:NSKeyValueObservingOptionInitial context:nil];}
//重写方法,当监听的数据模型发生改变时候,就会回调这个方法
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{NSLog(@"observeValueForKeyPath方法被调用了");NSLog(@"被修改的keyPath为:%@", keyPath);NSLog(@"被修改的对象为:%@", object);NSLog(@"新被修改的属性值为:%@", [change objectForKey:@"new"]);NSLog(@"被修改的上下文为:%@", context);
}-(void)dealloc
{[self.item removeObserver:self forKeyPath:@"name"];[self.item removeObserver:self forKeyPath:@"price"];
}
@end
main.m
#import "FKItemView.h"int main(int argc, char * argv[]) {@autoreleasepool {FKItemView *itemView = [FKItemView new];FKItem *item = [FKItem new];itemView.item = item;[itemView showItemInfo];item.name = @"chencaifeng";item.price = 79;}
}
3、运行结果
observeValueForKeyPath方法被调用了
被修改的keyPath为:name
被修改的对象为:<FKItem: 0x600000035360>
新被修改的属性值为:chencaifeng
被修改的上下文为:(null)
observeValueForKeyPath方法被调用了
被修改的keyPath为:price
被修改的对象为:<FKItem: 0x600000035360>
新被修改的属性值为:(null)
被修改的上下文为:(null)