IOS之通知
来源:互联网 发布:手机连接投影仪软件 编辑:程序博客网 时间:2024/05/22 03:15
通知是一种发送给一个或者多个观察者,用来通知其在程序中发生了某一个事件的消息。Cocoa中得通知机制遵循的是一种广播的模式。他是一种程序中事件的发起者或者处理者和其他想要知道该事件的对象沟通的一种方式。
通知机制的核心就是一个进程中单一实例的对象,被叫做通知中心(NSNotificationCenter)。当一个对象发布一个通知时,通知会被先发送到通知中心。通知中心的作用相当于是交流所.
#import <Foundation/Foundation.h>@interface King : NSObject-(void)sendMessage;@end
#import "King.h"@implementation King-(void)sendMessage{ NSNotification *notification = nil; notification = [NSNotification notificationWithName:@"message" object:self userInfo:[NSDictionary dictionaryWithObject:@"king" forKey:@"name"]]; [[NSNotificationCenter defaultCenter] postNotification:notification];}@end
#import <Foundation/Foundation.h>@interface Worker : NSObject-(void)say:(NSNotification *)notification;@end
#import "Worker.h"@implementation Worker-(id)init{ self = [super init]; if(self){ [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(say:) name:@"message" object:nil]; } return self;}-(void)say:(NSNotification *)notification{ NSDictionary *dic = [notification userInfo]; NSLog(@"%@",[dic objectForKey:@"name"]);}-(void)dealloc{ [[NSNotificationCenter defaultCenter] removeObserver:self name:@"message" object:nil]; [super dealloc];}@end
#import <Foundation/Foundation.h>#import "King.h"#import "Worker.h"int main(int argc, const char * argv[]){ King *king = [[King alloc] init]; Worker *worker = [[Worker alloc] init]; [king sendMessage]; [king release]; [worker release]; return 0;}
通知和KVO的区别
KVO只能监听属性的变化,通过NSString类型的属性名来实现。实现了监听,当属性值发生变化时,会自动通知观察者,不用再添加代码了。但是观察者得持有被观察者的引用,以便被观察者注册成为观察者,耦合性太高,不利于代码维护。
NSNotification比较灵活,可以监听内容不局限于属性的变化,还可以对多种多样的状态变化进行监听,监听范围广,使用也灵活。但是需要被观察者手动发送通知,观察者注册监听之后才能进行响应,比KVO多了发送通知的一步。但是观察者注册监听不需要被观察者的引用,没有耦合性,利于代码的维护
0 0
- ios之通知
- IOS 之 通知NSNotificationCenter
- IOS之通知
- iOS 之通知
- iOS开发之 通知
- iOS开发之自定义通知
- 11.ios之通知机制
- iOS开发之通知机制
- ios开发系列之通知
- ios激情详解之通知
- IOS学习笔记之通知
- iOS学习基础教程之通知
- iOS开发之通知中心
- ios开发之本地通知
- ios SDK开发之键盘通知
- [转载]IOS开发之----远程推送通知
- ]IOS开发之----远程推送通知
- IOS开发之----远程推送通知
- Euler_problem_18 for python
- 手机里的文件格式化了怎么找回
- 一种新型智能胎儿监护系统的研究与设计
- 【android基础学习之六】——常用效果1
- 解决fedora下无线网络不能用的问题
- IOS之通知
- 学习中
- 利用反射获得泛型的实际类型参数
- 怎么追女孩
- 怎样成为一名android开发者(转)
- 叙旧房子小夹子肉第三方开始让他一人一艘
- ZigBee终端怎样检测协调器或路由器已不在网络中
- 你创建微信公众账号了吗?别闲着,来做微信营销吧
- 费马小定理