4、直接改变课程信息对比
- #import "Student.h"
- #import "Course.h"
- #import "PageView.h"
- int main(int argc, const char * argv[])
- {
- @autoreleasepool {
- Student *student = [[[Student alloc]init]autorelease];
- [student changeCourseName:@"数学课"];
- NSLog(@"初始值:%@", [student valueForKey:@"courseName"]);
- //创建页面实例
- PageView *pageview = [[[PageView alloc]init:student]autorelease];
- [student setValue:@"化学课" forKey:@"courseName"];
- [student changeCourseName:@"英语课"];
- NSLog(@"直接改变的课程为:%@", [student valueForKey:@"courseName"]);
- }
- return 0;
- }
直接调用changeCourseName方法改变课程,打印结果:
2012-07-24 16:32:06.230 objectiveC[2240:403] 初始值:数学课
2012-07-24 16:32:06.237 objectiveC[2240:403] PageView课程被改变了
2012-07-24 16:32:06.238 objectiveC[2240:403] PageView新课程是:化学课老课程是:数学课
2012-07-24 16:32:06.239 objectiveC[2240:403] 直接改变的课程为:英语课
可以看到,这时Pageview的回调没被调用到。说明只有通过键值编码(KVC)改变的值,才会回调观察者注册的方法。
这里是苹果官网的关于KVO的文档,英文好的朋友可以看看:https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/KeyValueObserving/KeyValueObserving.html#//apple_ref/doc/uid/10000177-BCICJDHA
