码迷,mamicode.com
首页 > 其他好文 > 详细

KVO键值观察简述

时间:2015-08-07 13:35:11      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:

KVO 键值观察,简单来说就是为一个key添加一个观察者,当key的值发生改变的时候会发送通知,在接到通知的时候会有回调方法被调用

#import "ViewController.h"

@interface ViewController (){

    NSMutableDictionary * myDict;
}

@end

@implementation ViewController

- (IBAction)dasdas:(id)sender {
    
    //改变key的值
    NSString * key = [myDict objectForKey:@"key"];
    if ([key isEqualToString:@"key1"]) {
        
        [myDict setValue:@"key2" forKey:@"key"];
    }else {
    
        [myDict setValue:@"key1" forKey:@"key"];;
    }
    key = [myDict objectForKey:@"key"];
    NSLog(@"%@",key);
}

- (void)dealloc {

    //移除观察者
    [myDict removeObserver:self forKeyPath:@"key"];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    myDict = [[NSMutableDictionary alloc] init];
    [myDict setValue:@"key1" forKey:@"key"];
    
    //添加观察者
    [myDict addObserver:self forKeyPath:@"key" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
    
}

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

//观察者观察的对象发生改变的时候调用的方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {

    if ([keyPath isEqualToString:@"key"]) {
        
        NSString * key = [(NSDictionary *)object objectForKey:@"key"];
        if ([key isEqualToString:@"key1"]) {
            
            self.view.backgroundColor = [UIColor greenColor];
        }else {
        
            self.view.backgroundColor = [UIColor orangeColor];
        }
    }
}


@end


KVO键值观察简述

标签:

原文地址:http://my.oschina.net/u/2253117/blog/489029

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!