设计模式 观察者 NSNotificationCenter
来源:互联网 发布:ubuntu鼠标指针主题 编辑:程序博客网 时间:2024/05/29 11:32
默认的广播站,类似 NSUserDefault 的共享实例
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
注册观察者,开始收听广播,此处代码一般放在 viewWillAppear 中,并在 viewWillDisappear 中停止监听
[center addObserver:(id)observer // 收听广播的观察者,控制器是最常见的观察者,所以此参数通常为self selector:(SEL)@selector(execute:) // 处理广播的方法,收到名为name的广播后调用此方法 name:(NSString *)name // 广播名称 object:(id)sender // 指定收听特定的对象发出的广播,通常nil,表示收听所有发送者的广播
实现响应广播的方法
- (void)execute:(NSNotification *)notification { notification.name // 广播站名称,对应注册时的 name 参数 notification.object // 发送此通知的对象,对应注册时的 sender 参数 notification.userInfo // 广播传递的信息,取决于广播的类型 if(notification.object && [notification.object isKindOfClass:[Test class]]){ //do something }}
结束收听,关掉广播
[[NSNotificationCenter defaultCenter] removeObserver:self]; // 在离开堆前被调用,可以在这里关闭广播 -(void) dealloc{ [[NSNotificationCenter defaultCenter] removeObserver:self]; }
发出广播,即通知相应的观察者
[[NSNotificationCenter defaultCenter] postNotificationName:@"NOTIFICATION_NAME" object:nil];//或者用下面几行代码,明确的 notification 示例Test *test = [[Test alloc] init];NSNotification *notification = [NSNotification notificationWithName:@"NOTIFICATION_NAME" object:test];[[NSNotificationCenter defaultCenter] postNotification:notification];
示例,接受字体尺寸改变的广播
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];[center addObserver:self selector:@selector(fontSIzeChange:) name:UIContentSizeCategoryDidChangeNotification object:nil];
-(void)fontSIzeChange:(NSNotification *)notification{ // 处理字体尺寸改变的代码}
0 0
- 设计模式 观察者 NSNotificationCenter
- NSNotificationCenter观察者模式
- NSNotificationCenter(观察者模式) 的使用
- NSNotificationCenter的设计模式
- NSNotificationCenter 观察者
- NSNotificationCenter 与设计模式 (Observer)
- NSNotificationCenter 与设计模式 (Observer)
- 模式设计:观察者模式
- 设计模式-----观察者模式
- 设计模式-观察者模式
- 设计模式--观察者模式
- 设计模式:观察者模式
- 设计模式-----观察者模式
- 设计模式:观察者模式
- 设计模式-观察者模式
- 设计模式 观察者模式
- 设计模式-观察者模式
- 设计模式-【观察者模式】
- 28岁程序员转行,何去何从?
- hdu 2057 A + B Again
- 静态代理与动态代理二
- 读书笔记19:访问者模式
- css ie6,ie7,ie8 兼容性写法,CSS hack写法
- 设计模式 观察者 NSNotificationCenter
- leetcode之路027 Remove Element
- openssl使用
- 【暑期基础】P HDU 2015 偶数求和
- linux shell截取字符串
- android库工程jar打包和混淆
- 读书笔记20:中介者模式
- POJ 2723 && HDU 1816 Get Luffy Out(2-SAT+二分)
- 【暑期基础】Q HDU 2016 数据的交换输出