【非凡程序员】 OC第十节课 (KVO的应用一 开通银行卡短信提醒)

限于喜欢 提交于 2019-12-09 22:24:34

KVO就是一个对象监听自己或者别的对象的语法

它包括 1.注册  2.改值  3.回调  4.移除,一共四个方面(缺一不可)

这是一个银行卡监控余额的例子:

 

①.main函数
//  main.m
//  偷钱
//
//  Created by 非凡程序员 on 15/5/27.
//  Copyright (c) 2015年 非凡程序员. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "Person.h"
#import "Acount.h"
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...
        NSLog(@"Hello, World!");
       
        Person * person1=[[Person alloc]init];
        [person1 setValue:@"岁平" forKey:@"name"];
        [person1 setValue:@"20" forKey:@"age"];
        [person1 setValue:@"男" forKey:@"sex"];
       
        Acount * acount1=[[Acount alloc]init];
        [acount1 setValue:@"10000.555" forKey:@"money"];
        [acount1 setValue:@"2015-03-2" forKey:@"registerTime"];
        [acount1 setValue:@"123456" forKey:@"password"];
        //把钱包给人
        [person1 setValue:acount1 forKey:@"cc"];
        //注册  person1是监控者,account1是被监控者
        [acount1  addObserver:person1 forKeyPath:@"money" options:NSKeyValueObservingOptionNew |                NSKeyValueObservingOptionOld context:nil];
        //改值   //注册后每改一次值,就会调用一次 person.m里面的回调方法

        [acount1 setValue:@"33" forKey:@"money"];       

        [person1 setValue:@"55" forKeyPath:@"cc.money"];
      //移除   (该步骤不可省略)
        [acount1 removeObserver:person1 forKeyPath:@"money"]; 
    }
    return 0;
}

②.person.h文件
//
//  Person.m
//  偷钱
//
//  Created by 非凡程序员 on 15/5/27.
//  Copyright (c) 2015年 非凡程序员. All rights reserved.
//

#import "Person.h"

@implementation Person

////回调--------------- (重点)------------------//
-(void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    NSLog(@"更改后:%@ ",[object valueForKey:@"money"]);//输出新值

    NSLog(@"新值 %@[change valueForKeyPath:keyPath]);//输出新值

    NSLog(@"旧值%@",[change valueForKeyPath:NSKeyValueChangeOldKey]);//输出旧值
    NSLog(@"新值 %@[change valueForKeyPath:NSKeyValueChangeNewKey]);//输出新值

   NSLog(@"新值 %@[change valueForKeyPath:@"new"]);//输出新值

   NSLog(@"新值 %@[change valueForKeyPath:@"old"]);//输出旧值

    NSLog(@"%@,change );// 全部输出

}

-(void)dealloc
{
    NSLog(@"%@释放",_name);
}
@end

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!