iOS 设计模式-NSNotificationCenter 通知中心
通知介绍

初始化通知中心
// 初始化通知中心
NSNotificationCenter *center =[NSNotificationCenter defaultCenter];
注册通知监听器
通知中心(NSNotificationCenter)提供了方法来注册一个监听通知的监听器(Observer)
方法一:
- (void)addObserver:(id)observer selector:(SEL)aSelector name:(NSString *)aName object:(id)anObject;
- observer:监听器,即谁要接收这个通知
- aSelector:收到通知后,回调监听器的这个方法,并且把通知对象当做参数传入
- aName:通知的名称。如果为nil,那么无论通知的名称是什么,监听器都能收到这个通知
- anObject:通知发布者。如果为anObject和aName都为nil,监听器都收到所有的通知
方法二:
- (id)addObserverForName:(NSString *)name object:(id)obj queue:(NSOperationQueue *)queue
usingBlock:(void (^)(NSNotification *note))block;
- name:通知的名称
- obj:通知发布者
- block:收到对应的通知时,会回调这个block
- queue:决定了block在哪个操作队列中执行,如果传nil,默认在当前操作队列中同步执行
发布通知
通知中心(NSNotificationCenter)提供了相应的方法来帮助发布通知
取消注册通知监听器
- (void)removeObserver:(id)observer;
- (void)removeObserver:(id)observer name:(NSString *)aName object:(id)anObject;
- (void)dealloc {
//[super dealloc]; 非ARC中需要调用此句
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
实例代码
两个新闻机构(腾讯新闻、新浪新闻),每当发布新闻时,通知订阅了该新闻的用户。
新闻机构类 NewsCompany.h
// 新闻发布机构 #import <Foundation/Foundation.h> @interface NewsCompany : NSObject
/**
* 机构名称
*/
@property (nonatomic, copy) NSString *name;
@end
NewsCompany.m
#import "NewsCompany.h" @implementation NewsCompany @end
订阅者类
Person.h
#import <Foundation/Foundation.h> @interface Person : NSObject
/**
* 姓名
*/
@property (nonatomic, copy) NSString *name; - (void)newsCome:(NSNotification *)note;
@end
Person.m
#import "Person.h"
#import "NewsCompany.h" @implementation Person // 收到通知后,回调监听器的这个方法,并且把通知对象当做参数传入
- (void)newsCome:(NSNotification *)note
{
// 通知的发布者
NewsCompany *obj = note.object; NSLog(@"%@接收到了%@发出的通知,通知内容是:%@", self.name, obj.name, note.userInfo);
} // 一般在监听器销毁之前取消注册
- (void)dealloc
{
// [super dealloc];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
通知中心
main.m
#import <Foundation/Foundation.h>
#import "Person.h"
#import "NewsCompany.h" int main(int argc, const char * argv[])
{
@autoreleasepool {
// 1.初始化机构
NewsCompany *tx = [[NewsCompany alloc] init];
tx.name = @"腾讯新闻"; NewsCompany *sina = [[NewsCompany alloc] init];
sina.name = @"新浪新闻"; // 2.初始化2个人
Person *zhangsan = [[Person alloc] init];
zhangsan.name = @"张三"; Person *lisi = [[Person alloc] init];
lisi.name = @"李四"; // 初始化通知中心
NSNotificationCenter *center =[NSNotificationCenter defaultCenter]; // 3.注册通知监听器
// zhangsan只监听tx发出的junshi_news_come通知
[center addObserver:zhangsan selector:@selector(newsCome:) name:@"junshi_news_come" object:nil];
// lisi监听tx发的所有通知
[center addObserver:lisi selector:@selector(newsCome:) name:nil object:tx]; // 4.发布通知
// tx发布了一则叫做junshi_news_come的通知
[center postNotificationName:@"junshi_news_come"
object:tx
userInfo:@{@"title" : @"伊拉克战争停止了",
@"intro" : @"伊拉克战争停止了.........."}]; // sina发布了一则叫做junshi_news_come的通知
[center postNotificationName:@"yule_news_come"
object:sina
userInfo:@{@"title" : @"",
@"intro" : @""}]; }
return ;
}
运行结果:

其它通知
UIDevice设备通知
- UIDeviceOrientationDidChangeNotification // 设备旋转
- UIDeviceBatteryStateDidChangeNotification // 电池状态改变
- UIDeviceBatteryLevelDidChangeNotification // 电池电量改变
- UIDeviceProximityStateDidChangeNotification // 近距离传感器(比如设备贴近了使用者的脸部)
键盘通知
- UIKeyboardFrameBeginUserInfoKey // 键盘刚开始的frame
- UIKeyboardFrameEndUserInfoKey // 键盘最终的frame(动画执行完毕后)
- UIKeyboardAnimationDurationUserInfoKey // 键盘动画的时间
- UIKeyboardAnimationCurveUserInfoKey // 键盘动画的执行节奏(快慢)
使用方式
监听:
// 2.监听键盘的通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
取消监听:
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
最后
在使用过程中,我们需要注意,最后通知的线程,是由发起通知的线程决定的。如果发起通知是主线程,则收到的通知也是主线程。
更新UI必须要在主线程中更新,因此,我们最好在所有的通知回调中,都判断一下,如果当前线程不是主线程,则回到主线程。
宏定义如下,这个在SDWebImage里有这个宏定义。
#define dispatch_main_async_safe(block)\
if ([NSThread isMainThread]) {\
block();\
} else {\
dispatch_async(dispatch_get_main_queue(), block);\
}
iOS 设计模式-NSNotificationCenter 通知中心的更多相关文章
- iOS之NSNotificationCenter通知中心使用事项
其实这里的通知和之前说到的KVO功能很想,也是用于监听操作的,但是和KVO不同的是,KVO只用来监听属性值的变化,这个发送监听的操作是系统控制的,我们控制不了,我们只能控制监听操作,类似于Androi ...
- NSNotificationCenter通知中心
概述 NSNotificationCenter通知中心,通常用于一对一或者一对多的消息传递,即当一个地方改变时,要求改变其他的一些地方,例如当网络请求回来了新的数据,需要刷新本地信息和本地内存里面的界 ...
- iOS开发之通知中心(NSNotificationCenter)
前言 面向对象的设计思想是把行为方法封装到每一个对象中,以用来增加代码的复用性.正是这种分散封装,增加了对象之间的相互关联,总是有很多的对象需要彼此了解以及相互操作! 一个简单示例说明这种交互产生的对 ...
- iOS生命周期 & 通知中心
笔记内容 学习笔记-段玉磊 Stanford course View Controller Lifecycle 这篇文是我记载Developing iOS 7 Apps公开课 第5课的笔记 UITex ...
- IOS NSNotification Center 通知中心的使用
通知中心,它是IOS程序内部的一种消息广播机制,通过它,可以实现无引用关系的对象之间的通信.通知中心他是基于观察者模式,它只能进行程序内部通信,不能跨应用程序进程通信.当通知中心接受到消息后会根据设置 ...
- NSNotificationCenter 通知中心传值
1.NSNotification 这个类可以理解为一个消息对象,其中有三个成员变量. 这个成员变量是这个消息对象的唯一标识,用于辨别消息对象. @property (readonly, copy) N ...
- iOS 通知中心 NSNotificationCenter
iOS开发中,每个app都有一个通知中心,通知中心可以发送和接收通知. 在使用通知中心 NSNotificationCenter之前,先了解一下通知 NSNotification. NSNotific ...
- 通知中心 NSNotificationCenter 的简单使用方法
NSNotificationCenter(通知中心) [注意]需再dealloc中移除观察者 获取通知中心单例对象 NSNotificationCenter *center=[NSNotifi ...
- 通知中心 NSNotificationCenter
NSNotificationCenter 通知中心提供了一种在程序内广播信息的途径,一个NSNotificationCenter对象本质上是一个通知分发表(notification dispatch ...
随机推荐
- 分块+莫队||BZOJ3339||BZOJ3585||Luogu4137||Rmq Problem / mex
题面:P4137 Rmq Problem / mex 题解:先莫队排序一波,然后对权值进行分块,找出第一个没有填满的块,直接for一遍找答案. 除了bzoj3339以外,另外两道题Ai范围都是1e9. ...
- asp.net core 1.1 项目升级至 asp.net core 2.0 preview 2 与正式版
这两天把一个 asp.net core 1.1 的项目迁移到了 asp.net core 2.0 preview 2 ,在这篇随笔中记录一下. 如果项目在有 global.json 文件,需要删除或修 ...
- 查看线程的进程id
import os from threading import Thread def f1(n): print(n) print('%d号线程的id是%s'%(n,os.getpid())) if _ ...
- Newtonsoft.Json 转换DateTime类型为字符串时,串内部会有一个T。解决方案
使用Newtonsoft.Json 转换DateTime类型时,若使用标准转换,则字符串内会有一个T(虽然再转换成DateTime没有问题). 若要转换成DateTime没有T,可以加上特性: pub ...
- php安全
1.会话安全性 会话固化 一种获取有效回话标识符的方法,他将运行恶意用户通过强制使用回话ID来轻松模拟一个真实用户 攻击方法:<a href="http://a.com/index.p ...
- 优云软件又双叒通过CMMI ML3评估 , 研发和质量管理水平创新高
2017年第三季度,SEI授权的主任评估师对优云软件研发中心进行了CMMI软件能力成熟度模型评估,优云软件顺利通过复评. 这是继2011年12月优云软件首次通过CMMI ML3级的评估认证以来,第二次 ...
- python练习题-day4
1.写代码,有如下列表,按照要求实现每一个功能 li = ["alex", "WuSir", "ritian", "barry&q ...
- 前端 HTML body标签相关内容 常用标签 盒子标签 div
盒子标签 div <div>可定义文档的分区 division的缩写 译:区 <div> 标签可以把文档分割为独立的.将他们进行分区 div在浏览器中,默认是不会增加任何的效果 ...
- 火币网API文档——WebSocket API Reference
订阅 KLine 数据 market.$symbol.kline.$period 成功建立和 WebSocket API 的连接之后,向 Server 发送如下格式的数据来订阅数据: { " ...
- 可快速生成增删curd改查功能的插件
仿造Django中的admin自己实现增删改查.模糊搜索.批量操作.条件筛选.popup功能的插件 1.创建组件 首先创建一个app,这里取名为stark,在settings.py中将其进行注册 IN ...