iOS笔记—KVO

KVO 是监听键值。只要对象被监听的属性发生变化,那么就会执行监听方法(回调方法)

//
//  ViewController.m
//  KVO
//
//  Created by hhg on 15/9/28.
//  Copyright (c) 2015年 hhg. All rights reserved.
//

#import "ViewController.h"

@interface ViewController () {
    UILabel *label;
}
@property (nonatomic ,strong) Person *john;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(100, 100, 100, 30);
    button.backgroundColor = [UIColor greenColor];
    [self.view addSubview:button];
    [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];

    label = [[UILabel alloc]initWithFrame:CGRectMake(100, 170, 100, 30)];
    [self.view addSubview:label];

    //创建数据对象
    self.john = [[Person alloc]init];
    [self.john  setValue:@"hello" forKey:@"name"];


    //设定监听属性
    [self.john addObserver:self forKeyPath:@"name" options:(NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld) context:nil];

    [self.john addObserver:self forKeyPath:@"age" options:(NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld) context:nil];


}

//监听方法
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {

    NSLog(@"%@",keyPath);

    label.text = [NSString stringWithFormat:@"%03d",arc4random()%10000];
    NSLog(@"change = %@",change);

}


-(void)buttonClick:(UIButton *)butt {
    unsigned int k = arc4random()%100;
    [self.john setValue:[NSNumber numberWithUnsignedInt:k] forKey:@"age"];
    [self.john  setValue:@"hi" forKey:@"name"];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end

person类只有两个属性

//
//  Person.h
//  KVO
//
//  Created by hhg on 15/9/28.
//  Copyright (c) 2015年 hhg. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface Person : NSObject {
    NSUInteger age;
}

@property (nonatomic,assign) NSString *name;

@end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值