开发中我们常常需要监听到某些属性值的变化而做一些相应的事情,比如说展示筹款进度的进度条,如果进度发生改变,我们是希望进度条也会跟随变化滚动,这个时候我们就可以通过KVO监听属性的办法满足这个需求.
以下为一个简单的使用KVO的demo
demo介绍,我们现在假设在一个界面上面有一个文字属性,里面展示的是人物的年龄,我们给这个年龄添加一个监听者,如果人物年龄发生变化,我们就让展示的文字属性值跟随改变.
.h文件的nian'lin
@interface HJPerson : NSObject
/** age */
@property(nonatomic, assign)NSInteger age;
@end
控制器的.m文件
#import "ViewController.h"
#import "HJPerson.h"
@interface ViewController ()
/** person */
@property(nonatomic, strong)HJPerson * person;
/** 展示的文字 */
@property(nonatomic, strong) UILabel *personAge;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//需求,让控制器能够监听到person年龄的变化,并且将最新的年龄显示到界面上去
HJPerson *person = [HJPerson new];
self.person = person;
person.age = 10;
UILabel *personAge = [UILabel new];
personAge.frame = CGRectMake(100, 100, 200, 200);
personAge.text = [NSString stringWithFormat:@"%zd",person.age];
personAge.backgroundColor = [UIColor cyanColor];
[self.view addSubview:personAge];
self.personAge = personAge;
[self.person addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionNew context:nil];
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
self.person.age = 20;
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
/**
NSLog(@"keyPath=%@,object=%@,change=%@,context=%@",keyPath,object,change,context);
keyPath=age,object=<HJPerson: 0x7fe64af086e0>,change={
kind = 1;
new = 20;
},context=(null)
*/
NSLog(@"keyPath=%@,object=%@,change=%@,context=%@",keyPath,object,change,context);
这里需要将NSNumber类型转换为字符串类型
NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
NSString *ageStr = [numberFormatter stringFromNumber:[change objectForKey:@"new"]];
self.personAge.text = ageStr;
}
@end
效果如下