KVO:全名为:KeyValue Observing,直译为:基于键值的观察者。
KVO主要用于视图交互方面,比如界面的某些数据变化了,界面的显示也跟着需要变化,那就要建立数据和界面的关联。
//自己的代码
//test_class.h
#import <Foundation/Foundation.h>
@interface test_class : NSObject
@end
//test_class.m
#import "test_class.h"
@implementationtest_class
//这里实现方法
-(void) observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context
{
if([keyPath isEqual:@"balance"])
{
NSLog(@"invoke observefun! old value is[%@],new value is[%@]",change[@"old"],change[@"new"]);
}
}
@end
//account_class.h
#ifndefKVO_test_account_class_h
#defineKVO_test_account_class_h
#import <Foundation/Foundation.h>
@interface Account : NSObject
#pragma mark - 属性
@property (nonatomic,assign) float balance;
- (void) change:(float)NewBalance;
- (void) newChange:(float)value;
@end
#endif
//account_class.m
#import <Foundation/Foundation.h>
#import "account_class.h"
@implementation Account
- (void) change:(float)NewBalance
{
_balance = NewBalance;
NSLog(@"invoke change:fun! new value = [%f]",NewBalance);
}
-(void) newChange:(float)value
{
self.balance =value;
NSLog(@"invokenewChange: fun! new value = [%f]",value);
}
@end
//main.m
#import <Foundation/Foundation.h>
#import "account_class.h"
#import "test_class.h"
int main(intargc, const char* argv[])
{
@autoreleasepool
{
Account *account2 = [[Account alloc]init];
account2.balance = 100;
test_class *testObj = [[test_class alloc]init];
//给account2对象添加监视器(testObj)用来监视某个键的值是否发生变化(这里是balance属性),监视器类中要实现observeValueForKeyPath...的方法
[account2 addObserver:testObj forKeyPath:@"balance"
options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld
context:nil];
//通过KVC修改值,会报给监视器
[account2 setValue:@"200" forKey:@"balance"];
//通过存取方法修改属性值,会报给监视器
account2.balance = 300;
//直接对值进行修改,未调用属性方法,不会报告给监视器
[account2 change:400];
//使用属性方法修改值,会报给监视器,实际上会先调用监视器的方法
[account2 newChange:600];
//去掉特定对象对特定键路径的监视
[account2 removeObserver:testObj forKeyPath:@"balance"];
//此时修改值就不在报给监视器了
[account2 setValue:@500 forKey:@"balance"];
NSLog(@"last value is[%ld]",[[account2 valueForKey:@"balance"]integerValue]);
}
return 0;
}