KVO的简单用法

//  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一样

    [self removeObserver:self forKeyPath:@"string"];

    

    [super dealloc];

}


- (void)viewDidLoad {

    [super viewDidLoad];

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

    

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

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

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

    [button setBackgroundColor:[UIColor greenColor]];

    

    [button addTarget:self action:@selector(buttonDidPress:) forControlEvents:UIControlEventTouchUpInside];

    

    [self.view addSubview:button];


    

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

    // 参数1:观察者

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

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

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

    

    [self addObserver:self forKeyPath:@"string" options:NSKeyValueObservingOptionNew context:@"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"];

    [self setValue:@"aa" forKey:@"string"];

}


- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值