KVO.非常简单的键值监听模式

iOS中有两种支持机制:Notification和KVO(Key-Value Observing)

KVO是iOS中的一个核心概念,简单理解就是:关注Model某个数据(Key)的对象可以注册为监听器,一旦Model某个Key的Value发生变化,就会广播给所有的监听器

KVO:KVO是一个怎么样的Cocoa机制?

答:Kvo(Key Value Coding)是cocoa中用来设值或取值的协议(NSKeyValueCoding),跟java的ejb有点类似。都是通过对变量和函数名进行规范达到方便设置类成员值的目的.它是Cocoa的一个重要机制,它有点类似于Notification,但是,它提供了观察某一属性变化的方法,而Notification需要一个发送notification的对象,这样KVO就比Notification极大的简化了代码。这种观察-被观察模型适用于这样的情况,比方说根据A(数据类)的某个属性值变化,B(view类)中的某个属性做出相应变化。对于推崇MVC的cocoa而言,kvo应用价值很高。

kvo的使用方法:

1、注册: -(void)addObserver:(NSObject *)anObserver forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context keyPath就是要观察的属性值,options给你观察键值变化的选择,而context方便传输你需要的数据(注意这是一个void型)

2、实现变化方法:

-(void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context change里存储了一些变化的数据,比如变化前的数据,变化后的数据;如果注册时context不为空,这里context就能接收到。是不是很简单?kvo的逻辑非常清晰,实现步骤简单

 

//
//  ViewController.m
//  KVO_TestDemo
//
//  Created by yingkong1987 on 12-7-24.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "ViewController.h"
#import "DataModel.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize dataModel;

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    DataModel *mod = [[DataModel alloc] init];
    self.dataModel = mod;
    [mod release];
    [self.dataModel addObserver:self forKeyPath:@"dataString" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

#pragma mark - ButtonClick Method
- (void)changeValueButtonClick:(id)sender
{
//    [self.dataModel setValue:[NSNumber numberWithInt:(arc4random()%20)] forKey:@"needObserverValue"];
//    self.dataModel.needObserverValue = arc4random()%20;
    self.dataModel.dataString = [NSString stringWithFormat:@"今天捡到%d块钱",arc4random()%20];
}

#pragma mark - KVO Delegate
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    NSLog(@"%@",keyPath);
    NSLog(@"%@ %@",object,self.dataModel);
    NSLog(@"%@",change);
    NSLog(@"%@",self.dataModel.dataString);
}

@end
//
//  DataModel.h
//  KVO_TestDemo
//
//  Created by yingkong1987 on 12-7-24.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface DataModel : NSObject

@property (nonatomic,retain)NSString *dataString;

@end
原文地址:https://www.cnblogs.com/yingkong1987/p/2606580.html