@interface HYBStudent : NSObject
@property (nonatomic, copy) NSString *studentName;
@property (nonatomic, assign) CGFloat grade;
@end
#import "ViewController.h"
#import "HYBStudent.h"
@interface ViewController ()
@property (nonatomic, strong) HYBStudent *student;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.student = [[HYBStudent alloc] init];
self.student.studentName = @"李四";
self.student.grade = 90.f;
// add observer to the student
[self.student addObserver:self forKeyPath:@"grade" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionInitial context:nil];
[self performSelector:@selector(changeGrade) withObject:nil afterDelay:4.0];
}
- (void)changeGrade {
self.student.grade = 100.0f;
}
- (void)observeValueForKeyPath:(nullable NSString *)keyPath
ofObject:(nullable id)object
change:(nullable NSDictionary *)change
context:(nullable void *)context {
if ([keyPath isEqualToString:@"grade"]) {
NSLog(@"student %@‘s grade is %f‘",
self.student.studentName, self.student.grade);
}
}
- (void)dealloc {
// Don‘t forget to remove observer
[self.student removeObserver:self forKeyPath:@"grade" context:nil];
}
@end
2015-08-28 16:18:00.537 KVODEMO[1281:476192] student 李四‘s grade is 90.000000‘
2015-08-28 16:18:04.539 KVODEMO[1281:476192] student 李四‘s grade is 100.000000‘
- (void)observeValueForKeyPath:(nullable NSString *)keyPath
ofObject:(nullable id)object
change:(nullable NSDictionary *)change
context:(nullable void *)context {
if ([keyPath isEqualToString:@"grade"]) {
NSLog(@"张三的同学成绩发生了变化: %@‘s grade is %f‘",
((HYBStudent *)object).studentName, ((HYBStudent *)object).grade);
}
}
// 再次实例化一个学生实体,作为student的同学
self.zhangStudent = [[HYBStudent alloc] init];
self.zhangStudent.studentName = @"张三";
self.zhangStudent.grade = 59;
[self.student addObserver:self.zhangStudent
forKeyPath:@"grade"
options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionInitial
context:nil];
2015-08-28 16:43:51.234 KVODEMO[1317:480175] student 李四‘s grade is 90.000000‘
2015-08-28 16:43:51.235 KVODEMO[1317:480175] 张三的同学成绩发生了变化: 李四‘s grade is 90.000000‘
2015-08-28 16:43:55.236 KVODEMO[1317:480175] 张三的同学成绩发生了变化: 李四‘s grade is 100.000000‘
2015-08-28 16:43:55.237 KVODEMO[1317:480175] student 李四‘s grade is 100.000000‘
- (void)observeValueForKeyPath:(nullable NSString *)keyPath
ofObject:(nullable id)object
change:(nullable NSDictionary *)change
context:(nullable void *)context;
// Don‘t forget to remove observer
[self.student removeObserver:self forKeyPath:@"grade" context:nil];
[self.student removeObserver:self.zhangStudent forKeyPath:@"grade" context:nil];
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/woaifen3344/article/details/48054729