KVO:Key Value Observing,顾名思义,键值观察。
KVO主要用于视图交互方面,比如界面的某些数据变化了,界面的现实也跟着需要变化,那就要简历数据和页面的关联。
下面通过实例讲解KVO的简单使用。
KVO自动调用简单使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
#import <Foundation/Foundation.h>
@interface Student : NSObject { NSString *_name; NSString *_courseName; int _age; }
- (void)changeCourseName:(NSString *) newCourseName; - (void)changeAge:(int) age; @end
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
#import "Student.h"
@implementation Student
-(void)changeCourseName:(NSString *)newCourseName { _courseName = newCourseName; }
- (void)changeAge:(int)age { _age = age; }
@end
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
#import "PageView.h" #import "Student.h"
@implementation PageView
-(id)init:(Student *)initStudent { if (self == [super init]) { student = initStudent; [student addObserver:self forKeyPath:@"courseName" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:nil]; } return self; }
-(void)dealloc { [student removeObserver:self forKeyPath:@"courseName" context:nil]; }
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context { if ([keyPath isEqual:@"courseName"]) { NSLog(@"PageView课程被改变了"); NSLog(@"PageView新课程是: %@, 老课程是: %@", [change objectForKey: @"new"], [change objectForKey: @"old"]); } }
@end
|
测试代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
- (void)useKVO { Student *student = [[Student alloc] init]; [student changeCourseName:@"语文课"]; [student changeAge:19]; NSLog(@"初始值: %@ %@", [student valueForKey: @"courseName"], [student valueForKey: @"age"]); PageView *page = [[PageView alloc]init:student]; [student setValue:@"数学课" forKey:@"courseName"]; [student changeCourseName:@"英语课"]; //这样直接改变不会触发observer,说明只有通过键值编码(KVC)改变的值,才会回调观察者注册的方法。 [student willChangeValueForKey:@"age"]; [student changeAge:20]; [student didChangeValueForKey:@"age"]; 输出结果: 2016-01-04 14:47:36.794 testOC[31517:1071934] 初始值: 语文课 2016-01-04 14:47:36.795 testOC[31517:1071934] PageView课程被改变了 2016-01-04 14:47:36.795 testOC[31517:1071934] PageView新课程是: 英语课, 老课程是: 语文课 **/ }
|
输出结果:
1 2 3
|
2016-01-05 17:59:15.642 testOC[42635:1792662] 初始值: 语文课 19 2016-01-05 17:59:15.643 testOC[42635:1792662] PageView课程被改变了 2016-01-05 17:59:15.643 testOC[42635:1792662] PageView新课程是: 数学课, 老课程是: 语文课
|
可以看到,只有通过KVC方式赋值才会触发Observer。
不懂KVC的童鞋,请看这篇文章: KVC
不懂观察者模式的童鞋可以看看这篇文章:Observer
参考:http://www.cnblogs.com/stoic/archive/2012/07/24/2606784.html