iPhone软件开发的时候会遇到这种情况:打开APP后会在后台运行某个方法,例如下载文件,下载完成后可能需要调用某个方法来刷新界面,这时候可能没法在下载的函数中回调。NSNotificationCenter(通知)是一个很好的选择。

通知使用起来灰常的简单:

1、定义通知:

[[NSNotificationCenter defaultCenter] addObserver: self         selector: @selector(callBack)             name: @"back"            object: nil];

2、定义通知中使用的方法:

- (void)callBack{  NSLog(@"i am back."); }

3、调用通知:

- (void)getIT{  NSLog(@"get it.");  //发出通知  [[NSNotificationCenter defaultCenter] postNotificationName:@"back" object:self]; }

在调用通知的时候程序会在整个项目中寻找此通知的名称,找到后发出请求,因此通知的名称需要在整个项目中唯一。

1. 定义一个方法

-(void) update{       }

2. 对象注册,并关连消息

[[NSNotificationCenter defaultCenter]

addObserver:self selector:@selector(update) name:@"update" object:nil]

3. 在要发出通知消息的地方

[[NSNotificationCenter defaultCenter]

postNotificationName:@"update" object:nil];

具体如何使用 Notifications

http://blog.sina.com.cn/s/blog_5df7dcaf0100c0q2.html

////////////////////////////////////////

第十四章: 使用 Notifications

用户可能使用RaiseMan并打开了几个document, 然后他发现紫色的背景颜色实在是不利于阅读文档正文.

于是,他打开Preferences panel修改背景颜色,不过令人失望的是,已经存在的文档的背景颜色不会跟着改变.

于是,这个用户可能会写信给你告诉你这些. 你也许会回复:"defualts会在document创建的时候才读取,

保存document在打开"实际上,用户想说明的是他希望程序能立马刷新已经打开的文档. 如果这样,那该怎么做呢?

我们需要把所有打开的document用一个list记录起来么?

--- 什么是Notification? ---

这个要求其实也很容易实现. 每个运行中的application都有一个NSNotificationCenter的成员变量,

它的功能就类似公共栏. 对象注册关注某个确定的notification(如果有人捡到一只小狗,就去告诉我).

我们把这些注册对象叫做 observer. 其它的一些对象会给center发送notifications(我捡到了一只小狗).

center将该notifications转发给所有注册对该notification感兴趣的对象. 我们把这些发送notification的对象叫做 poster

很多的标准Cocoa类会发送notifications: 在改变size的时候,Window会发送notification;

选择table view中的一行时,table view会发送notification;我们可以在在线帮助文档中查看到标准cocoa对象发送的notification

在我们的例子中,我们将MyDocumet对象注册为observer. 而preference controller在用户改变color时将发送notification.

MyDocument在接受到该notification后改变background color

在MyDocument对象释放前,我们必须从notification center移除我们注册的observer. 一般我们在dealloc方法中做这件事

-- Notifications 不是什么 --

当程序员们听到notification center的时候, 他们可能会联想到IPC(进程间通讯).他们认为:

"我在一个程序中创建一个observer,然后在另外一个程序中发送一个notification". 这个设计没有办法工作的,

notification center允许同一个程序中的不同对象通许,它不能跨越不同的程序 [Notification 就是设计模 式中的 观察者模式,

cocoa为我们实现了该模式, 就像Java也有同样的实现一样]

-- NSNotification 和 NSNotificationCenter

Notification对象非常简单. 它就是poster要提供给observer的信息包裹. notification对象有两个重要的成员变量:

name 和 object. 一般object都是指向poster(为了让observer在接受到notification时可以回调到poster)

所以,notification有两个方法

- (NSString *)name

- (id)object

NSNotificaitonCernter是架构的大脑了.它允许我们注册observer对象, 发送notification, 撤销observer对象注册

下面是它的一些常用方法

+ (NSNotificationCenter *)defaultCenter

返回notification center [类方法,返回全局对象, 单件模式.cocoa的很多的全局对象都是通过类似方法实现]

- (void)addObserver:(id)anObserver

selector:(SEL)aSelector

name:(NSString *)notificationName

object:(id)anObject

注册anObserver对象:接受名字为notificationName, 发送者为anObject的notification. 当anObject发送名字

为notificationName的notification时, 将会调用anObserver的aSelector方法,参数为该notification 如图14.1

. 如果notificationName为nil. 那么notification center将anObject发送的所有notification转发给observer

. 如果anObject为nil.那么notification center将所有名字为notificationName的notification转发给observer

- (void)postNotification:(NSNotification *)notification

发送notification至notification center 如图14.2

- (void)postNotificationName:(NSString *)aName

object:(id)anObject

创建并发送一个notification

- (void)removeObserver:(id)observer

移除observer

-- 发送一个Notification --

发送notification是其中最简单的步骤了,所以我们从它开始实现.当我们接收到changeBackgroundColor:消息时,

PreferenceController对象发送一个notification.

我们将notification命名为@"BNRColorChanged" ,我们使用一个全局常量来指定.(有经验的程序员会使用一个前缀,

这样避免和其他组件定义的notification混淆)打开PreferenceController.h 添加下面的的外部申明

extern NSString * const BNRColorChangedNotification;

在PreferenceController.m中定义常量

NSString * const BNRColorChangedNotification = @"BNRColorChanged";

在PreferenceController.m修改changeBackgroundColor:方法

- (IBAction)changeBackgroundColor:(id)sender

{

NSColor *color = [colorWell color];

NSData *colorAsData =

[NSKeyedArchiver archivedDataWithRootObject:color];

[[NSUserDefaults standardUserDefaults] setObject:colorAsData

forKey:BNRTableBgColorKey];

NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];

NSLog(@"Sending notification");

[nc postNotificationName:BNRColorChangedNotification object:self];

}

-- 注册成为Observer --

要注册一个observer, 我们必须提供几个要数: 要成为observer的对象;所感兴趣的notification的名字;

当notification发送时要调用的方法. 我们也可以指定要关注莫个对象的notification.(比如说,我们需要

关注莫个特定的window的resize的notification)

编辑MyDocument类的init方法

- (id)init

{

if (![super init])

return nil;

employees = [[NSMutableArray alloc] init];

NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];

[nc addObserver:self

selector:@selector(handleColorChange:)

name:BNRColorChangedNotification

object:nil];

NSLog(@"Registered with notification center");

return self;

}

同时在dealloc方法,将MyDocument从notification center中移除

- (void)dealloc

{

[self setEmployees:nil];

NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];

[nc removeObserver:self];

[super dealloc];

}

-- 处理Notification --

当一个notification发生时, handleColorChange:方法将被调用. 目前我们在方法中简单的打印一些log.

- (void)handleColorChange:(NSNotification *)note

{

NSLog(@"Received notification: %@", note);

}

编译运行程序,看到了我们想要的log了吧

-- userInfo Dictionary --

notification对象的object变量是poster,如果我们想要notification对象传递更多的信息,

我们可以使用user info dictionary. 每个notification对象有一个变量叫 userInfo, 它是一个NSDictionary对象,

用来存放用户希望随着notification一起传递到observer的其它信息. MyDocument将使用它来得到要改变的color.

在PreferenceController.m添加userInfo

- (IBAction)changeBackgroundColor:(id)sender

{

NSColor *color = [sender color];

NSData *colorAsData;

colorAsData = [NSKeyedArchiver archivedDataWithRootObject:color];

[[NSUserDefaults standardUserDefaults] setObject:colorAsData

forKey:BNRTableBgColorKey];

NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];

NSLog(@"Sending notification");

NSDictionary *d = [NSDictionary dictionaryWithObject:color

forKey:@"color"];

[nc postNotificationName:BNRColorChangedNotification

object:self

userInfo:d];

}

在MyDocument.m,从userInfo中读取到color

- (void)handleColorChange:(NSNotification *)note

{

NSLog(@"Received notification: %@", note);

NSColor *color = [[note userInfo] objectForKey:@"color"];

[tableView setBackgroundColor:color];

}

打开几个窗口,并改变背景颜色,现在,那些打开的窗口的背景颜色立马就变了.

-- 思考 --

通常当你将自己的一个对象设置为cocoa某个标准对象的delegate的时候,你同时或许也对该标准对象的notification感兴趣.

例如,我们实现一个window的delegate来处理 windowShouldClose: , 我们也许会对 NSWindowDidResizeNotification

这样的notification感兴趣.

如果一个cocoa标准对象有一个delegate,同时它也发送notification的话, cocoa对象会自动将它的delegate对象注册

成为observer来接受接受自己的notification. 如果我们实现了一个delegate,那么delegate[也就是我们的对象]

要怎样声明来接受notification呢?[方法的名字是什么?]

方法名字其实很简单: 以notification名字为基准, 先将NS前缀去掉,接着将第一个字母改为小写. 在将后面的Notification去掉,

然后加个冒号:. 例如,为了能接受到window的NSWindowDidResizeNotification, delegate可以实现方法:

- (void)windowDidResize:(NSNotification *)aNotification

当window改变大小时,这个方法将自动调用. 对于NSWindow,我们可以在.h或是帮助文档中找到类似的notification

来实现notification方法.

-- 挑战 --

当程序不再是active状态是,让程序发出beep. 当unactive时,NSApplication会发送

NSApplicationDidResignActiveNotification的notificaiton. 而我们的AppController是NSApplication的delegate.

函数NSBeep()可以用来发出beep声音

下边的转自:http://hi.baidu.com/wwssttt/item/27450a26318ea0899c63d1ae

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.

- (void)viewDidLoad

{

[super viewDidLoad];

self.view.backgroundColor = [UIColor colorWithRed:0.05 green:0.6 blue:0.3 alpha:1.0];

self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:0.2 green:0.3 blue:0.5 alpha:1];

count = 0;

timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTimer:) userInfo:nil repeats:YES];

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotification:) name:@"Note" object:nil];

}

-(void)updateTimer:(NSTimer*)time{

count++;

self.title = [NSString stringWithFormat:@"%d",count];

if (count%5 == 0) {

[[NSNotificationCenter defaultCenter] postNotificationName:@"Note" object:nil];

}

}

-(void)receiveNotification:(NSNotification*)note{

UIAlertView* noteView = [[UIAlertView alloc] initWithTitle:nil message:@"You receive a notification!!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];

[noteView show];

[noteView release];

}

- (void)viewDidUnload

{

[[NSNotificationCenter defaultCenter] removeObject:self];

[super viewDidUnload];

// Release any retained subviews of the main view.

// e.g. self.myOutlet = nil;

if (timer != nil) {

[timer release];

timer = nil;

}

}

以下内容转自http://blog.sina.com.cn/s/blog_793cad6e0100sa6x.html

什么是Notification?

这个要求其实也很容易实现. 每个运行中的application都有一个NSNotificationCenter的成员变量,它的功能就类似公共栏. 对象注册关注某个确定的notification(如果有人捡到一只小狗,就去告诉我). 我们把这些注册对象叫做 observer. 其它的一些对象会给center发送notifications(我捡到了一只小狗). center将该notifications转发给所有注册对该notification感兴趣的对象. 我们把这些发送notification的对象叫做poster

很多的标准Cocoa类会发送notifications: 在改变size的时候,Window会发送notification; 选择table view中的一行时,table view会发送notification;我们可以在在线帮助文档中查看到标准cocoa对象发送的notification

在对象释放前,我们必须从notification center移除我们注册的observer. 一般我们在dealloc方法中做这件事

NSNotification类

提供给observer的信息包裹. notification对象有两个重要的成员变量: name 和 object.

- (NSString *)name;

- (id)object;

- (NSDictionary *)userInfo;我们想要notification对象传递更多的信息

+ (id)notificationWithName:(NSString *)aName object:(id)anObject;

+ (id)notificationWithName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary*)aUserInfo;

NSNotificationCenter类

+ (id)defaultCenter;返回notification center [类方法,返回全局对象, 单件模式.cocoa的很多的全局对象都是通过类似方法实现]

- (void)addObserver:(id)observer selector:(SEL)aSelector name:(NSString *)aName object:(id)anObject;

如果notificationName为nil. 那么notification center将anObject发送的所有notification转发给observer

. 如果anObject为nil.那么notification center将所有名字为notificationName的notification转发给observer

- (void)postNotification:(NSNotification *)notification;

- (void)postNotificationName:(NSString *)aName object:(id)anObject;

- (void)postNotificationName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary*)aUserInfo;

- (void)removeObserver:(id)observer;

- (void)removeObserver:(id)observer name:(NSString *)aName object:(id)anObject;

【转载】iPhone开发之NSNotificationCenter(通知)的使用方法相关推荐

  1. 详解iPhone开发之Objective-C和 C 混编

    详解iPhone开发之Objective-C和 C 混编 2011-07-29 15:47 佚名 互联网 字号:T | T 本文介绍的是详解iPhone开发之Objective-C和C混编,介绍了ip ...

  2. 【无限互联】iOS开发视频教程— 2.8 iPhone开发之swtch语句

    核心内容 1. switch语句语法 2. 防止case穿透,与break结合使用 视频地址:iPhone开发之swtch语句

  3. iphone开发之Google地图实现…

    原文地址:iphone开发之Google地图实现 学习随笔 作者:若水一叶 摘自博文:http://tergol.blog.163.com/blog/static/170695028201081961 ...

  4. android qt 串口通信,Qt串口通信开发之QSerialPort模块详细使用方法与实例

    Qt串口通信开发之QSerialPort模块详细使用方法与实例 发布时间:2020-10-23 12:19:05 来源:脚本之家 阅读:111 作者:沧海一笑-dj Qt串口通信基础及名词说明 串口通 ...

  5. android 接口实现方法,Android应用开发之Android 请求网络接口实现方法

    本文将带你了解Android应用开发之Android 请求网络接口实现方法,希望本文对大家学Android有所帮助. public   class Fragment01 extends Fragmen ...

  6. mipcms模板开发之block(块)内容调用方法

    文章目录[隐藏] 块内容调用前言 块内容调用图片描述 块内容调用教程 块内容调用前言 最近几天在筹划资源网站,网站采用MIPCMS内容管理系统,前端采用 bootstrap4 写了一套模板. 在模板编 ...

  7. iOS开发之UIDevice通知

    UIDevice类提供了一个单例对象,它代表着设备,通过它可以获得一些设备相关的信息,比如电池电量值(batteryLevel).电池状态(batteryState).设备的类型(model,比如iP ...

  8. iphone开发之C++和Objective-C混编

    C++和Objective-C混编(官方文档翻译) 原文网址: http://developer.apple.com/iphone/library/documentation/Cocoa/Concep ...

  9. iPhone开发之SQLite

    现在网站开发和软件开发,数据库的支持是少不了的:在iPhone开发中,作为数据持久化的解决方案中,SQLite是不错的选择,它既轻量占用资源少,又可以方便嵌入到程序中,在一些嵌入式设备中有着广泛使用. ...

最新文章

  1. Python中的生产者与消费者模式(转载)
  2. debian8下给postgresql9.5编译配置pgpool-II-3.5
  3. Python logging动态调整日志等级
  4. CVPR 2019 | 旷视研究院提出Re-ID新方法VPM,优化局部成像下行人再识别
  5. 获取两个数据的交集_MySQL交集和差集的实现方法
  6. mysql怎么加固_mysql安装及加固
  7. 【离散数学】集合的特征函数
  8. Python 实现邮件发送功能(进阶)
  9. 小学计算机应用到英语课教案,人教版小学英语三年级上册unit one hello!文具单词教学信息技术应用成果(教学设计方案).doc...
  10. oracle中jason串,在oracle中使用json
  11. WPF 控件专题 TextBox控件详解
  12. 物联网(IoT)行业的决策管理应用
  13. 超酷炫技:10 个牛逼的单行代码编程技巧
  14. 利用html5画出五角星画出星空
  15. 面对恐惧和压力,你是怎么做的?
  16. swift UI专项训练21 网页浏览器
  17. 外企就很舒服?聊聊我在外企的工作体验
  18. 从18路诸侯讨董卓,谈如何对抗51%攻击
  19. 《雨巷》-- 戴望舒
  20. char* p 和 char p[]区别及应用

热门文章

  1. 保留thinkvantage一键恢复功能的Linux与vista双系统安装
  2. qt实现汽车销售管理系统(一)-- 登录界面的实现
  3. MyBatis 源码分析之 SqlSession 创建
  4. js 判断是windows系统和苹果系统
  5. 可能是全网最好的 Spock 单测入门文章!
  6. 程浩[迅雷网创始人]
  7. linux中anaconda更换源
  8. Android 项目必备(二十七)-->加密和解密
  9. Linux运维工具Supervisor(进程管理工具)
  10. String 类型操作 16进制转10进制