一. 先看下官方对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 通知详解+异步发送和接收通知

  

IOS NSNotification 通知的更多相关文章

  1. iOS NSNotification通知

    通知中心(NSNotificationCenter) 通知(NSNotification) 一个完整的通知一般包含3个属性:(注意顺序) - (NSString *)name;  通知的名称 - (i ...

  2. iOS - Notification 通知

    1.Notification 通知中心实际上是在程序内部提供了消息广播的一种机制,它允许我们在低程度耦合的情况下,满足控制器与一个任意的对象进行通信的目的.每一个 iOS 程序(即每一个进程)都有一个 ...

  3. IOS Notification 通知中心

    1.     通知中心概述 通知中心实际上是在程序内部提供了消息广播的一种机制.通知中心不能在进程间进行通信.实际上就是一个二传手,把接收到的消息,根据内部的一个消息转发表,来将消息转发给需要的对象. ...

  4. How Not to Crash #3: NSNotification通知引起的崩溃

    How Not to Crash #3: NSNotification通知引起的崩溃html, body {overflow-x: initial !important;}html { font-si ...

  5. IOS中通知中心(NSNotificationCenter)

    摘要 NSNotification是IOS中一个调度消息通知的类,采用单例模式设计,在程序中实现传值.回调等地方应用很广.   IOS中通知中心NSNotificationCenter应用总结 一.了 ...

  6. ios 消息通知

    苹果的通知分为本地通知和远程通知,这里主要说的是远程通知 历史介绍 iOS 3 - 引入推送通知UIApplication 的 registerForRemoteNotificationTypes 与 ...

  7. iOS中通知传值

    NSNotification 通知中心传值,可以跨越多个页面传值, 一般也是从后面的页面传给前面的页面.   思路: 第三个界面的值传给第一个界面. 1. 在第一个界面建立一个通知中心, 通过通知中心 ...

  8. IOS开发-通知与消息机制

    在多数移动应用中不论什么时候都仅仅能有一个应用程序处于活跃状态.假设其它应用此刻发生了一些用户感兴趣的那么通过通知机制就能够告诉用户此时发生的事情. iOS中通知机制又叫消息机制,其包含两类:一类是本 ...

  9. IOS 本地通知 UILocalNotification

    IOS 本地通知 UILocalNotification [本文章第四部分中的代码逻辑来自网上的借鉴,并非我自己原创] 大概一个月前,我开始跟着做IOS项目了.学习C++,了解Objective-C, ...

随机推荐

  1. 关于MySQLServer5.6配置问题

    配置MySQL MySQL数据库下载以后在根目录添加my.ini配置文件 需要注意的是配置文件的二个属性: basedir=D:\MySqlServer # mysql所在目录 根据需求改 MySQL ...

  2. IntelliJ IDEA 2017.2 下载和破解方法

    一.IntelliJ IDEA 2017 下载地址  http://www.jetbrains.com/idea/#chooseYourEdition 要下载付费版的,免费版的很多功能不能用 二.破解 ...

  3. select, poll, epoll笔记

    看网络通信框架,netty, thrift,java nio等,最后都会通过select, poll, epoll或者socket等进行通信.查了些网页,总结一下.做个笔记 1. Socket单线程阻 ...

  4. 解决python3缺少zlib的问题

    解决python3缺少zlib的问题 Table of Contents 1. 安装zlib 2. 重新编译安装python 3. 补充说明 在使用python3运行spark时,报缺少zlib的错误 ...

  5. 提交自己的包到 npm 中

    npm npm全称Node Package Manager,是node.js的模块依赖管理工具.使用github管理NPM包的代码,并定期提交至NPM服务器:npm官网 提交自己开发的NPM包 创建p ...

  6. css 小常识

    一.vertical-align可以采用负值(正/负值根据基线上下移动),也可以采用百分比值,而这个百分比值不是相对于字体大小或者其他什么属性计算的,而是相对于line-height计算的. 此外,w ...

  7. HCNA配置静态LACP模式链路聚合

    1.静态LACP模式 静态LACP模式是一种利用LACP协议进行聚合参数协商.确定活动接口和非活动接口的链路聚合方式.该模式下,需手工创建Eth-Trunk,手工加入Eth-Trunk成员接口,由LA ...

  8. Using nxlog4go for Testing Environment

    nxlog4go is very simple to use without any configuring, setting. For example: package main import ( ...

  9. Docker镜像提交命令commit的工作原理和使用方法

    在本地创建一个容器后,可以依据这个容器创建本地镜像,并可把这个镜像推送到Docker hub中,以便在网络上下载使用. 下面我们来动手实践. docker pull nginx:1.15.3 用命令行 ...

  10. ABAP的语法高亮是如何在浏览器里显示的

    这篇文章的原文我发表在SAP官方社区上:https://blogs.sap.com/2018/03/09/how-abap-syntax-highlight-is-implemented-in-web ...