iOS--KVO

ViewController.m#

//
//  ViewController.m
//  KVO
//

//

#import "ViewController.h"
#import "Person.h"
@interface ViewController ()


@property(nonatomic, strong)Person *person;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
   self.person = [[Person alloc] init];
    
    _person.name = @"dongliang";
    
    //添加观察者 注册
    [_person addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew context:(__bridge void *)self];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    
    [self.view addGestureRecognizer:tap];
    
}

//观察者的方法
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    
    //keypath 是观察的属性
    NSLog(@"---------keypath:%@",keyPath);
    //被观察的对象
    NSLog(@"---------object:%@",object);
    //新旧值
    NSLog(@"---------change:%@",change);//change是字典
    
    NSLog(@"---------context:%@",context);
    
    if ([change[NSKeyValueChangeNotificationIsPriorKey]boolValue]) {
        NSLog(@"1");
        NSLog(@"值改变之前");
    } else{
        NSLog(@"2");
        NSLog(@"值改变之后");
    }
    

    
//    self.view.backgroundColor = [UIColor greenColor];
    
    //context的作用就是传值/////////////////////////////
    ViewController *vc = (__bridge ViewController *)context;

    vc.view.backgroundColor = [UIColor greenColor];
}



-(void)tapAction:(UITapGestureRecognizer *)sender{
    
    //我注意你很久了
    _person.name = @"zhaoyu";
    
    
}


/**
 *  移除观察者!!!!!!!!!!!!!!!!!
 */

-(void)dealloc{
    
    [_person removeObserver:self forKeyPath:@"name"];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

Person.h#

//
//  Person.h
//  KVO
//

//

#import 

@interface Person : NSObject

@property(nonatomic, strong)NSString *name;


@end

Person.m#

//
//  Person.m
//  KVO
//

//

#import "Person.h"

@implementation Person

@end

你可能感兴趣的:(iOS--KVO)