kvo知识

一、KVO是什么?

KVO 是 Objective-C 对观察者设计模式的一种实现。【另外一种是:通知机制(notification),详情参考:iOS 趣谈设计模式——通知】;
KVO提供一种机制,指定一个被观察对象(例如A类),当对象某个属性(例如A中的字符串name)发生更改时,对象会获得通知,并作出相应处理;【且不需要给被观察的对象添加任何额外代码,就能使用KVO机制】
在MVC设计架构下的项目,KVO机制很适合实现mode模型和view视图之间的通讯

二、实现方法

//对象设置监听属性 age
[self.model addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionNew context:nil];
//监听对象属性改变后的动作
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    
    if ([keyPath isEqualToString:@"age"]) {
        self.label.text = [NSString stringWithFormat:@"%d",self.model.age];
        
    }
}

三、代码

@interface ViewController ()
@property (nonatomic, strong) UILabel *label;

@property (nonatomic, strong) PeopleModel *model;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    
    UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(100, 100, 100, 30)];
    [button setBackgroundColor:[UIColor redColor]];
    [button addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(100, 150, 100, 30)];
    label.textColor = [UIColor redColor];
    [self.view addSubview:label];
    
    self.label = label;
    
    self.model = [[PeopleModel alloc]init];
    self.model.age = 25;
    
    //对象设置监听属性 age
    [self.model addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionNew context:nil];

    
}
- (void)buttonAction{
    //对象属性的改变
    self.model.age = self.model.age + 1;
}
//监听对象属性改变后的动作
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    
    if ([keyPath isEqualToString:@"age"]) {
        self.label.text = [NSString stringWithFormat:@"%d",self.model.age];
        
    }
}

你可能感兴趣的:(kvo知识)