3、实现观察
在main函数中
- #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"];
- }
- return 0;
- }
新建一个student的实例,设置他的课程是数学课,然后创建页面类的时候,用student初始化。这是页面类已经观察着学生的课程了。
再给课程设置新的值为化学课。这时候运行打印结果:
2012-07-24 16:29:21.561 objectiveC[2192:403] 初始值:数学课
2012-07-24 16:29:21.565 objectiveC[2192:403] PageView课程被改变了
2012-07-24 16:29:21.566 objectiveC[2192:403] PageView新课程是:化学课老课程是:数学课
可以看到Pageview类中的回调被调用,Pageview接收到学生课程数据更新的信息。
