KVO就是一個對象監聽本身或者別的對象的語法程序員
它包括 1.註冊 2.改值 3.回調 4.移除,一共四個方面(缺一不可)函數
這是一個銀行卡監控餘額的例子:spa
①.main函數
// main.m
// 偷錢
//
// Created by 非凡程序員 on 15/5/27.
// Copyright (c) 2015年 非凡程序員. All rights reserved.
//code
#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"]; server
[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.
//rem
#import "Person.h"it
@implementation Personio
////回調--------------- (重點)------------------//
-(void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
NSLog(@"更改後:%@ ",[object valueForKey:@"money"]);//輸出新值import
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