iOS 简单的描述KVO使用

//

//  ViewController.m

//  KVOtest

//

//  Created by Mac on 15/10/17.

//  Copyright © 2015年 聂小波. All rights reserved.

//

#import "ViewController.h"

@interface ViewController ()

@property (nonatomic, strong) UIButton *kvobtn;

@end

@implementation ViewController

- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    

    _kvobtn=[UIButton new];

    _kvobtn.tag=10;

    

    //对属性添加值改变监听

    [_kvobtn addObserver:self forKeyPath:@"tag" options:NSKeyValueObservingOptionNew context:nil];

    

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

        //改变属性值

        _kvobtn.tag=11;

        

    });

    

}

#pragma mark- KVO获得值改变调用

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{

    if ([keyPath isEqualToString:@"tag"]) {

        NSLog(@"===============changed===============");

    }

}

#pragma mark- 移除监听,如果没有移除会导致崩溃

-(void)dealloc{

    [self removeObserverFromUIButton:_kvobtn];

    [self removeNotification];

}

-(void)removeObserverFromUIButton:(UIButton *)kvobtn{

    [kvobtn removeObserver:self forKeyPath:@"tag"];

    

}

-(void)removeNotification{

    [[NSNotificationCenter defaultCenter] removeObserver:self];

}

@end

原文地址:https://www.cnblogs.com/niexiaobo/p/4888655.html