開發(fā)中我們常常需要監(jiān)聽到某些屬性值的變化而做一些相應(yīng)的事情,比如說展示籌款進度的進度條,如果進度發(fā)生改變,我們是希望進度條也會跟隨變化滾動,這個時候我們就可以通過KVO監(jiān)聽屬性的辦法滿足這個需求.
以下為一個簡單的使用KVO的demo
demo介紹,我們現(xiàn)在假設(shè)在一個界面上面有一個文字屬性,里面展示的是人物的年齡,我們給這個年齡添加一個監(jiān)聽者,如果人物年齡發(fā)生變化,我們就讓展示的文字屬性值跟隨改變.
.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];
//需求,讓控制器能夠監(jiān)聽到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類型轉(zhuǎn)換為字符串類型
NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
NSString *ageStr = [numberFormatter stringFromNumber:[change objectForKey:@"new"]];
self.personAge.text = ageStr;
}
@end
效果如下
KVO簡單使用.gif