KVO的简单用法

来源:互联网 发布:win32 串口编程 编辑:程序博客网 时间:2024/06/01 19:56

//  Created by wjn on 15/9/30.

//  Copyright © 2015 wlm. All rights reserved.

//


#import "ViewController.h"


@interface ViewController ()


@property (nonatomic,retain) NSString *string;


@end


@implementation ViewController


- (void)dealloc {

    

    //切记一定要在完成之后移除掉 - ARC一样

    [selfremoveObserver:selfforKeyPath:@"string"];

    

    [superdealloc];

}


- (void)viewDidLoad {

    [superviewDidLoad];

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

    

   UIButton *button = [UIButtonbuttonWithType:UIButtonTypeCustom];

    button.frame =CGRectMake(0,20, self.view.frame.size.width,40);

    [button setTitle:@"KVO"forState:UIControlStateNormal];

    [button setBackgroundColor:[UIColorgreenColor]];

    

    [buttonaddTarget:selfaction:@selector(buttonDidPress:)forControlEvents:UIControlEventTouchUpInside];

    

    [self.viewaddSubview:button];


    

    // KVO一个类监听自己的属性(成员变量)的变化

    // 参数1:观察者

    //参数2:要观察的对象

    //参数3:一旦发生改变,观察的结果是取新值还是旧值

    //参数4:一旦发生改变,可以传递的内容

    

    [selfaddObserver:selfforKeyPath:@"string"options:NSKeyValueObservingOptionNewcontext:@"BOOM"];

}


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

    // 系统的方法

    //当观察到的属性改变之后,自动调用这个方法

   NSLog(@"%@", keyPath);

   NSLog(@"%@", object);

   NSLog(@"%@", change);

   NSLog(@"%@", context);

}


//-(NSMutableArray *)mutableArray {

//    if (!_mutableArray) {

//        self.mutableArray = [NSMutableArray arrayWithObject:@"a"];

//    }

//    return _mutableArray;

//}


- (void)buttonDidPress:(UIButton *)sender {

//    [self.mutableArray addObject:@"a"];

    [selfsetValue:@"aa"forKey:@"string"];

}


- (void)didReceiveMemoryWarning {

    [superdidReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end


0 0
原创粉丝点击