KVO

/*KVO 键值观察对象和对象之间传递消息

 一,概述

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

 二,使用方法

 系统框架已经支持KVO,所以程序员在使用的时候非常简单。

 1. 注册,指定被观察者的属性,

 2. 实现回调方法

 3. 移除观察*/

//person

#import <Foundation/Foundation.h>

#import "BankCount.h"

@interface Person : NSObject

{

    BankCount *aBankCount;

}

- (void)registerABankCount;//打开监听银行账号的能力

@end

#import "Person.h"

@implementation Person

- (id)init

{

    if (self = [super init]) {

        

        aBankCount = [[BankCountalloc] init];

    }

    returnself;

}

// Yu_e指向自己的指针

static void *Yu_e = (void *)&Yu_e;

- (void)registerABankCount

{

    //监听银行账号的变化过程

    [aBankCountaddObserver:selfforKeyPath:@"yu_e"options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOldcontext:Yu_e];

    //移除监听

    //[self removeObserver:object forKeyPath:@"yu_e"];

    //aBankCount增加一个监听者 self 去监听:yu_e

    //只要yu_e有变化就会让self知道

}

//监听的回调函数

//只要aBankCountyu_e有变化就会调用

//keyPath就是之前监听的yu_e

//object就是aBankCount

//change是一个字典里边包含了新、旧值

//context是一个私有变量Yu_e

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context

{

    if (context == Yu_e) {

        NSString *str = [change objectForKey:NSKeyValueChangeNewKey];

        NSLog(@"str = %@",str);

    }

    else

    {

        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];

    }

}

//BankCount

#import <Foundation/Foundation.h>

@interface BankCount : NSObject

@property (nonatomic, assign) float yu_e;

@end

#import "BankCount.h"

@implementation BankCount

- (id)init

{

    self = [super init];

    if (self) {

        [NSTimerscheduledTimerWithTimeInterval:1.0ftarget:selfselector:@selector(yu_eUpdate:) userInfo:nilrepeats:YES];

    }

    returnself;

}

- (void)yu_eUpdate:(id)arg

{

    float f = self.yu_e;

    f += arc4random() % 100;

    self.yu_e = f;//1、不能_yu_e = f;

    

    [self setYu_e:f];//2

    

    [selfsetValue:[NSNumbernumberWithFloat:f] forKey:@"yu_e"];//3

    

    [selfwillChangeValueForKey:@"yu_e"];//4

    _yu_e = f;

    [selfdidChangeValueForKey:@"yu_e"];

}

@end

//调用

Person *p = [[Person alloc] init];

[p registerABankCount];

[[NSRunLoop currentRunLoop] run];

原文地址:https://www.cnblogs.com/chenhaosuibi/p/3442536.html