你好,游客 登录 注册 搜索
背景:
阅读新闻

Objective-C语法之KVO的使用

[日期:2012-07-26] 来源:blog.csdn.net/totogo2010  作者:totogo2010 [字体:大 中 小]

2、页面类实现

.h文件

  1. #import <Foundation/Foundation.h>   
  2. @class Student;  
  3. @interface PageView : NSObject  
  4. {  
  5.     Student *student;  
  6. }  
  7. -(id)init:(Student*)initStudent;  
  8. @end  

.m文件

  1. #import "PageView.h"   
  2. #import "Student.h"   
  3.   
  4. @implementation PageView  
  5. -(id)init:(Student*)initStudent  
  6. {  
  7.     if (self = [super init]) {  
  8.         student = initStudent;  
  9.         [student addObserver:self   
  10.                   forKeyPath:@"courseName"   
  11.                      options:NSKeyValueObservingOptionOld  
  12.                             |NSKeyValueObservingOptionNew context:nil];  
  13.     }  
  14.     return self;  
  15. }  
  16.   
  17. - (void) dealloc{   
  18.     [student removeObserver:self forKeyPath:@"courseName" context:nil];  
  19.     [super dealloc];   
  20. }  
  21.   
  22. -(void)observeValueForKeyPath:(NSString *)keyPath   
  23.                      ofObject:(id)object   
  24.                        change:(NSDictionary *)change   
  25.                       context:(void *)context  
  26. {  
  27.     if ([keyPath isEqual:@"courseName"]) {  
  28.         NSLog(@"PageView课程被改变了");  
  29.         NSLog(@"PageView新课程是:%@ 老课程是:%@", [change objectForKey:@"new"],[change objectForKey:@"old"]);  
  30.     }  
  31. }  
  32. @end  

init初始化时,向student实例添加观察者,在释放的时候移除观察者。

linux
相关资讯       Objective-C 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款