2、页面类实现
.h文件
- #import <Foundation/Foundation.h>
- @class Student;
- @interface PageView : NSObject
- {
- Student *student;
- }
- -(id)init:(Student*)initStudent;
- @end
.m文件
- #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];
- [super dealloc];
- }
- -(void)observeValueForKeyPath:(NSString *)keyPath
- ofObject:(id)object
- change:(NSDictionary *)change
- context:(void *)context
- {
- if ([keyPath isEqual:@"courseName"]) {
- NSLog(@"PageView课程被改变了");
- NSLog(@"PageView新课程是:%@ 老课程是:%@", [change objectForKey:@"new"],[change objectForKey:@"old"]);
- }
- }
- @end
init初始化时,向student实例添加观察者,在释放的时候移除观察者。
