IOS NSNotification 通知
一. 先看下官方对NSNotification通知的解释
1. NSNotification 通知
@interface NSNotification : NSObject <NSCopying, NSCoding>
接口通知,继承NSObject,实现NSCopying,NSCoding协议
A container for information broadcast through a notification center to all registered observers.
通过通知中心向所有注册观察员进行信息广播的容器
You don’t usually create your own notifications directly, but instead call the NSNotificationCenter methods.
你不能使用init去创建,而是调用NSNotificationCenter下的方法
2. NSNotificationCenter 通知中心
A notification dispatch mechanism that enables the broadcast of information to registered observers.
一种通知调度机制,该机制允许向注册观察员广播信息
Each running app has a defaultCenter notification center, and you can create new notification centers to organize communications in particular contexts.
每个运行的应用程序都有一个默认中心通知中心,您可以创建新的通知中心来组织特定上下文中的通信
A notification center can deliver notifications only within a single program; if you want to post a notification to other processes or receive notifications from other processes, use NSDistributedNotificationCenter instead.
通知中心只能在单个程序中传递通知;如果要将通知发布到其他进程或接收来自其他进程的通知,则使用NSdultDeNeTimeCenter代替
3. addObserver(_:selector:name:object:) 添加观察者方法
Adds an entry to the notification center's dispatch table with an observer, a selector, and an optional notification name and sender.
使用观察者、选择器和可选通知名称和发送器向通知中心的调度表添加条目
Declaration 声明

*observer 观察者
作为观察者注册的对象
*aSelector 选择器
当发出通知时,通知中心将向通知观察者发送通知的选择器
*aName 注册观察员的通知的名称
当NIL时,通知中心不使用通知的名称来决定是否将其传递给观察者
*anObject 观察者希望接收的通知对象
当NIL时,通知中心不使用通知的发送方来决定是否将其传递给观察者
4. postNotificationName(_:object:userInfo:) 发送通知消息的方法
Creates a notification with a given name, sender, and information and posts it to the notification center.
创建一个带有给定名称、发送者和信息的通知,并将其发布到通知中心
- (void)postNotificationName:(NSNotificationName)aName
object:(id)anObject
userInfo:(NSDictionary *)aUserInfo;
* aName
通知的名称
* anObject
发布通知的对象
* aUserInfo
关于通知的可选信息
5. removeObserver:name:object: 移除观察者的方法
从通知中心的调度表中移除指定观察者的所有指定条目。
如果你的应用程序瞄准了iOS 9和后来的Mac OS 10.11和以后,你就不需要在它的 dealloc 方法中注销观察者
- (void)removeObserver:(id)observer;
- (void)removeObserver:(id)observer
name:(NSString *)aName
object:(id)anObject;
二. 通知使用
示例背景: 用到两个ViewController,分别是 NotificationVC,TestVCViewController,当前代码写在NotificationVC中 1. 注册通知
// 初始化通知中心
NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
// 注册通知
[center addObserver:self selector:@selector(methodTest:) name:nil object:nil];
[center addObserver:self selector:@selector(sadNotif:) name:@"sad" object:nil];
[center addObserver:self selector:@selector(smileNotif:) name:@"smile" object:nil];
[center addObserver:self selector:@selector(sad2Notif:) name:@"sad" object:self]; [center addObserver:test selector:@selector(testNotif:) name:nil object:nil];
[center addObserver:test selector:@selector(sadNotif:) name:@"sad" object:nil];
[center addObserver:test selector:@selector(smileNotif:) name:@"smile" object:nil];
/* 用法说明
上面使用了两个监听器self,test,并且就参数三name,参数四object不同情况分别作出示例
[center addObserver:<#(nonnull id)#>
selector:<#(nonnull SEL)#>
name:<#(nullable NSNotificationName)#>
object:<#(nullable id)#>]
* 参数一 :监听器,即谁要接受这个通知
* 参数二 :回调方法,即接受通知时候,回调这个方法,作出响应
并把通知对象当作 参数 传入
* 参数三 : 通知的名称,标签
如果为nil,可以监听所有此类通知(具体还需要结合参数四)
如果有值,只监听这个名称的所有通知
* 参数四 :通知发布者
如果为nil,不关心是谁发布的通知,可根据参数三获取通知
如果有值,会获取这个值发布的通知,具体还需要看参数三是否一致 四个参数的作用:
参数一: 用于决定回调方法的位置,写在哪个类里面
参数二: 具体的回调方法,参数是通知对象
参数三: 是否需要监听指定的通知名称的通知
参数四: 是否需要监听指定的发布通告者的通知 注意: 如果通知名(参数三),发布通知者(参数四)都为nil
那么这个监听器的方法(参数二)可以回调所有此类通知
**/
2.发布通知:
// 发出通知
[center postNotificationName:@"sad" object:nil userInfo:@{@"title":@"伤心"}];
[center postNotificationName:@"sad" object:self userInfo:@{@"title":@"伤心"}];
[center postNotificationName:@"sad" object:test userInfo:@{@"title":@"伤心"}];
[center postNotificationName:@"smile" object:nil userInfo:@{@"title":@"开心"}];
[center postNotificationName:@"smile" object:test userInfo:@{@"title":@"开心"}];
[center postNotificationName:@"smile" object:self userInfo:@{@"title":@"开心"}];
/* 发布通知
[center postNotificationName:<#(nonnull NSNotificationName)#>
object:<#(nullable id)#>
userInfo:<#(nullable NSDictionary *)#>]
* 第一个参数,通知的方法名字,不能为nil
* 第二个参数,通知的发布者,可以为nil
* 第三个参数,通知所传递的信息,为字典格式
*/
3. 回调方法:
// self 中(NotificationVC)
- (void)smileNotif:(NSNotification *)notif{
NSLog(@"------1----%@/n",notif.userInfo);
}
- (void)sadNotif:(NSNotification *)notif{
NSLog(@"------2----%@/n",notif.userInfo);
}
- (void)methodTest:(NSNotification *)notif{
NSLog(@"------3----%@/n",notif.userInfo);
}
- (void)sad2Notif:(NSNotification *)notif{
NSLog(@"------4----%@/n",notif.userInfo);
} // TestVCViewController中
- (void)testNotif:(NSNotification *)notif{
NSLog(@"-----5-----%@/n",notif.userInfo);
}
- (void)smileNotif:(NSNotification *)notif{
NSLog(@"-----6-----%@/n",notif.userInfo);
}
- (void)sadNotif:(NSNotification *)notif{
NSLog(@"-----7-----%@/n",notif.userInfo);
} // 由于打印的太多,这里不提供打印结果了,有兴趣的可以copy,断点打印,查看 参数不同 的 注册通知 之间的区别
4. 移除通知:
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:test];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
// 移除方法
- (void)removeObserver:(id)observer;
- (void)removeObserver:(id)observer name:(NSString *)aName object:(id)anObject;
/*
removeObserver:是删除通知中心保存的调度表指定某个观察者的所有入口 removeObserver:name:object:是删除通知中心保存的调度表中某个观察者的指定某个入口
注意参数notificationObserver为要删除的观察者,不能为nil
**/
// 通常这样写 在viewWillAppear 中 addObserver,在viewWillDisappear 中 removeObserver
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(xxxx) name:@"xxxx" object:nil];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"xxxx" object:nil];
}
三. 扩展
1.block 通知
// 官方语法:
- (id <NSObject>)addObserverForName:(nullable NSNotificationName)name
object:(nullable id)obj
queue:(nullable NSOperationQueue *)queue
usingBlock:(void (^)(NSNotification *note))block API_AVAILABLE(macos(10.6),
ios(4.0), watchos(2.0), tvos(9.0)); /**
// The return value is retained by the system, and should be held onto by the caller in
// order to remove the observer with removeObserver: later, to stop observation.
返回值由系统保留,并由调用方保存。
顺序删除观测者,稍后,停止观察。
* 参数一 : 通知名称
* 参数二 : 监听者,即谁监听发出的通知
* 参数三 : 队列,决定block在哪个线程中区执行
如果传入nil,在发布通知的线程中去执行,即发布通知在哪个线程,block就在哪个线程中区执行
如果是耗时操作,放在子线程
* 参数四 : 监听到通知后的block回调 注意 : block函数返回值(示例:上文声明的 id object),由当前调用方保存,最后要移除
*/ object = [[NSNotificationCenter defaultCenter]addObserverForName:@"good"
object:self
queue:nil
usingBlock:^(NSNotification * _Nonnull note)
{
// 监听到通知会调用,不用单独写方法
NSLog(@"-----8-----%@/n",note.userInfo);
}]; // object 为声明的 id object [center postNotificationName:@"good" object:self userInfo:@{@"good":@"好极了"}];
[center postNotificationName:@"sad" object:self userInfo:@{@"sad":@"坏死了"}];
2.异步调用通知
即 通知放在异步方法中
* NSNotificationCenter消息的接受线程是基于发送消息的线程的,即 同步的
* 有时,你发送的消息可能不在主线程,但是操作UI必须在主线程,不然会出现不响应的情况。所以,在收到消息通知的时候,注意选择你要执行的线程
* 一般用于通知中执行耗时操作,异步执行,保证UI主线程的流程,不会“假死,卡死”
总结
通知通常用于监听需求属性,当属性发生变化,发出通知,通过回调方法作出改变,响应通知
参考博客:
iOS中 本地通知/本地通知详解 韩俊强的博客 (ps: 本地通知讲解的很详细,有兴趣可以下载他的demo)
iOS中通知中心(NSNotificationCenter)的使用总结
IOS中通知中心(NSNotificationCenter)的使用总结
IOS NSNotification 通知的更多相关文章
- iOS NSNotification通知
通知中心(NSNotificationCenter) 通知(NSNotification) 一个完整的通知一般包含3个属性:(注意顺序) - (NSString *)name; 通知的名称 - (i ...
- iOS - Notification 通知
1.Notification 通知中心实际上是在程序内部提供了消息广播的一种机制,它允许我们在低程度耦合的情况下,满足控制器与一个任意的对象进行通信的目的.每一个 iOS 程序(即每一个进程)都有一个 ...
- IOS Notification 通知中心
1. 通知中心概述 通知中心实际上是在程序内部提供了消息广播的一种机制.通知中心不能在进程间进行通信.实际上就是一个二传手,把接收到的消息,根据内部的一个消息转发表,来将消息转发给需要的对象. ...
- How Not to Crash #3: NSNotification通知引起的崩溃
How Not to Crash #3: NSNotification通知引起的崩溃html, body {overflow-x: initial !important;}html { font-si ...
- IOS中通知中心(NSNotificationCenter)
摘要 NSNotification是IOS中一个调度消息通知的类,采用单例模式设计,在程序中实现传值.回调等地方应用很广. IOS中通知中心NSNotificationCenter应用总结 一.了 ...
- ios 消息通知
苹果的通知分为本地通知和远程通知,这里主要说的是远程通知 历史介绍 iOS 3 - 引入推送通知UIApplication 的 registerForRemoteNotificationTypes 与 ...
- iOS中通知传值
NSNotification 通知中心传值,可以跨越多个页面传值, 一般也是从后面的页面传给前面的页面. 思路: 第三个界面的值传给第一个界面. 1. 在第一个界面建立一个通知中心, 通过通知中心 ...
- IOS开发-通知与消息机制
在多数移动应用中不论什么时候都仅仅能有一个应用程序处于活跃状态.假设其它应用此刻发生了一些用户感兴趣的那么通过通知机制就能够告诉用户此时发生的事情. iOS中通知机制又叫消息机制,其包含两类:一类是本 ...
- IOS 本地通知 UILocalNotification
IOS 本地通知 UILocalNotification [本文章第四部分中的代码逻辑来自网上的借鉴,并非我自己原创] 大概一个月前,我开始跟着做IOS项目了.学习C++,了解Objective-C, ...
随机推荐
- ExcelHelper office 导出
要是服务器上没有装着excel 可以用c#导出excel表吗 2009-08-10 17:36 风之成 | 分类:办公软件 | 浏览2279次 租用的空间 服务器上没有装着office excel,可 ...
- 利用Filter实现session拦截
1.在web.xml中配置 <!-- Session监听器 --> <filter> <filter-name>sessionValidateFilter</ ...
- MVC设置默认页面
方法1:在RouteConfig.cs文件中配置默认路由 public class RouteConfig { public static void RegisterRoutes(RouteColle ...
- IO流之File类
IO概述: 程序数据都是在内存中,程序运行结束,这些数据将清空,数据都都不能保存下来,下次程序启动的时候,想再把这些数据读出来继续使用,把数据持久化存储,就需要把内存中的数据存储到内存以外的其他持久化 ...
- Django组件——forms组件
一.校验字段功能 通过注册用户这个实例来学习校验字段功能. 1.模型:models.py from django.db import models # Create your models here. ...
- C++基础--字符串倒序输出
(一)用基本的数组实现 #include "stdafx.h" #include <stdio.h> #include <string.h> int mai ...
- android Viewpager取消预加载及Fragment方法的学习
1.在使用ViewPager嵌套Fragment的时候,由于VIewPager的几个Adapter的设置来说,都会有一定的预加载.通过设置setOffscreenPageLimit(int numbe ...
- Multidex (方法数超过限制的处理)
报错 : Conversion to Dalvik format failed: Unable to execute dex: method ID not in [0, 0xffff]: 65536 ...
- To find names containing exactly five characters, use “^”and “$”to match the beginning and end of the name, and five instances of “.”in between: mysql
To find names containing exactly five characters, use “^”and “$”to match the beginning and end of th ...
- windows下使用VNC进行远程连接
在 windows 电脑上安装 VNC,包含 VNC server 和 VNC viewer,如果仅需要被操控或操控他人,选择型下载安装 VNC server 或 VNC viewer 即可. 在需要 ...