Sian 发表于 2014-5-17 14:01:19

KVO 的基本理解

本帖最后由 Sian 于 2014-5-31 08:57 编辑

KVO概述:
KVO,即:Key-Value Observing,它提供一种机制,当指定的对象的属性被修改后,则对象就会接受到通知。
简单的说就是每次指定的被观察的对象的属性被修改后,KVO就会自动通知相应的观察者了。

KVO的优点:
当有属性改变,KVO会提供自动的消息通知。这样开发人员不需要自己去实现这样的方案:每次属性改变了就发送消息通知。
这是KVO机制提供的最大的优点。因为这个方案已经被明确定义,获得框架级支持,可以方便地采用。
开发人员不需要添加任何代码,不需要设计自己的观察者模型,直接可以在工程里使用。
其次,KVO的架构非常的强大,可以很容易的支持多个观察者观察同 一个属性,以及相关的值。

使用步骤如下:
1. 注册,指定被观察者的属性,
2. 实现回调方法
3. 触发回调方法
4. 移除观察

KVO使用例子代码如下:

###############Model(模型)###############
#import <Foundation/Foundation.h>
@interface Music : NSObject {
    // 监听的属性
    NSString *musicName;
}
@end

#import "Music.h"
@implementation Music
@end

###############ViewController(视图控制器)###############
#import <UIKit/UIKit.h>
@class Music;
@interface ViewController : UIViewController {
    Music *music;   
}
@property (nonatomic, retain) Music *music;
@end

@implementation ViewController
@synthesize music;

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    ;
   
    music = [ init];
   
    // 添加观察者注册当属性发生改变的时候被调用的
    ;
   
    // UILabel控件
    UILabel *musicLabel = [ initWithFrame:CGRectMake(20, 150, 280, 21)];
    musicLabel.font = ;
    musicLabel.textColor = ;
    musicLabel.tag = 100;
    ;
    ;
   
    // UITextField控件
    UITextField *musicTextField = [ initWithFrame:CGRectMake(20, 200, 280, 21)];
    musicTextField.font = ;
    musicTextField.placeholder = @"Please enter some words.";
    musicTextField.backgroundColor = ;
   
    // UITextField输入内容时候调用
    UIControlEventEditingChanged];
   
    ;
    ;

    self.view.backgroundColor = ;
}

- (void)textFieldDidChange:(id)sender {
    UITextField *textField = (UITextField *)sender;
    NSLog(@">>>>>>>>>>>>>>>%@",textField.text);
    // 修改正在监听的属性,将调用下面回调方法
    ;
}

// 只要Music类的"musicName"属性发生的变化都会触发到以下的方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    UILabel *label = (UILabel *);
    // 如果改变的属性是"musicName"
    if () {
      // 将 当前的musicName属性的值 赋值给UILabel
      label.text = ;
      // 输出改变前的值
      NSLog(@"old musicName is %@",);
      // 输出改变后的值
      NSLog(@"new musicName is %@",);      
    }
}

#pragma mark - Memory Management
- (void)dealloc {
    // 移除观察者
    ;
    ;
    ;
}

参考链接:http://blog.sina.com.cn/s/blog_621403ef0100ywc9.html


页: [1]
查看完整版本: KVO 的基本理解