关键类
NSNotification
用于描述通知的类,一个NSNotification对象就包含了一条通知的信息。
// 通知名称
@property (readonly, copy) NSNotificationName name;
// 通知携带的对象
@property (nullable, readonly, retain) id object;
// 发送通知时 配置的信息
@property (nullable, readonly, copy) NSDictionary *userInfo;
// 初始化方法
- (instancetype)initWithName:(NSNotificationName)name object:(nullable id)object userInfo:(nullable NSDictionary *)userInfo;
+ (instancetype)notificationWithName:(NSNotificationName)aName object:(nullable id)anObject;
+ (instancetype)notificationWithName:(NSNotificationName)aName object:(nullable id)anObject userInfo:(nullable NSDictionary *)aUserInfo;
NSNotificationCenter
是个单例类,负责管理通知的创建和发送,属于最核心的类了。它主要做三件事:
1、添加通知
2、发送通知
3、移除通知
// 全局唯一NSNotificationCenter对象
@property (class, readonly, strong) NSNotificationCenter *defaultCenter;
// 在通知中心添加一个通知
- (void)addObserver:(id)observer selector:(SEL)aSelector name:(nullable NSNotificationName)aName object:(nullable id)anObject;
// 发出一个通知
- (void)postNotification:(NSNotification *)notification;
- (void)postNotificationName:(NSNotificationName)aName object:(nullable id)anObject;
- (void)postNotificationName:(NSNotificationName)aName object:(nullable id)anObject userInfo:(nullable NSDictionary *)aUserInfo;
// 移除一个通知
- (void)removeObserver:(id)observer;
- (void)removeObserver:(id)observer name:(nullable NSNotificationName)aName object:(nullable id)anObject;
// 添加一个通知观察者,并在收到指定通知时执行指定的代码块
// 指定代码块的操作队列。如果为 nil,则在发送通知的线程上执行代码块。
// 返回的观察者对象 用于移除时使用
- (id <NSObject>)addObserverForName:(nullable NSNotificationName)name object:(nullable id)obj queue:(nullable NSOperationQueue *)queue usingBlock:(void (NS_SWIFT_SENDABLE ^)(NSNotification *note))block ;
注意:
1、添加通知时observer和sel都不可为空,通知名称name和携带对象object可以为空。
2、注册通知时应避免重复注册,会导致重复处理通知信息
3、使用block时,block内可能会持有外部对象,避免循环引用。
4、消息发送类型需要和注册时一致。
若注册时同时指定了名称和携带对象,发到那个消息时也要指定,否则无法收到消息(更多原因会在底层分析时介绍)
5、移除通知,ios9及macos10.11之后不需要手动调用,dealloc已经自动处理。
NSNotificationQueue
通知队列,用于异步发送消息。
这个异步并不是开启线程,而是把通知存到双向链表实现的队列里面,
等待某个时机触发时调用NSNotificationCenter的发送接口进行发送通知。
NSNotificationQueue最终还是调用NSNotificationCenter进行消息的分发。
NSNotificationQueue主要做了两件事:
1、添加通知到队列
2、删除通知
// 获取当前当前线程绑定的通知消息队列
@property (class, readonly, strong) NSNotificationQueue *defaultQueue;
// 指定通知中心创建通知队列
- (instancetype)initWithNotificationCenter:(NSNotificationCenter *)notificationCenter ;
// 把通知添加到队列中
- (void)enqueueNotification:(NSNotification *)notification postingStyle:(NSPostingStyle)postingStyle;
- (void)enqueueNotification:(NSNotification *)notification postingStyle:(NSPostingStyle)postingStyle coalesceMask:(NSNotificationCoalescing)coalesceMask forModes:(nullable NSArray<NSRunLoopMode> *)modes;
// 删除通知,把满足合并条件的通知从队列中删除
- (void)dequeueNotificationsMatching:(NSNotification *)notification coalesceMask:(NSUInteger)coalesceMask;
通知的发送时机
typedef NS_ENUM(NSUInteger, NSPostingStyle) {
NSPostWhenIdle = 1, // runloop空闲时发送通知
NSPostASAP = 2, // 当前通知调用或者计时器结束发出通知
NSPostNow = 3 // 立刻发送或在合并通知完成之后发送
};
通知的合并策略
// 有些时候同名通知只想存在一个,这时候就可以用到它了
typedef NS_OPTIONS(NSUInteger, NSNotificationCoalescing) {
NSNotificationNoCoalescing = 0,// 默认不合并
NSNotificationCoalescingOnName = 1,// 按照通知name合并,相同就合并
NSNotificationCoalescingOnSender = 2// 按照传入的object合并,相同就合并
};
底层分析
由于苹果没有对相关源码开放,所以以GNUStep源码为基础进行研究,虽然GNUStep不是苹果官方的源码,但很具有参考意义,根据实现原理来猜测和实践,更重要的还可以学习观察者模式的架构设计。
1、_GSIMapTable
* A rough picture is include below:
*
*
* This is the map C - array of the buckets
* +---------------+ +---------------+
* | _GSIMapTable | /----->| nodeCount |
* |---------------| / | firstNode ----+--\
* | buckets ---+----/ | .......... | |
* | bucketCount =| size of --> | nodeCount | |
* | nodeChunks ---+--\ | firstNode | |
* | chunkCount =-+\ | | . | |
* | .... || | | . | |
* +---------------+| | | nodeCount | |
* | | | fistNode | |
* / | +---------------+ |
* ---------- v v
* / +----------+ +---------------------------+
* | | * ------+----->| Node1 | Node2 | Node3 ... | a chunk
* chunkCount | * ------+--\ +---------------------------+
* is size of = | . | \ +-------------------------------+
* | . | ->| Node n | Node n + 1 | ... | another
* +----------+ +-------------------------------+
* array pointing
* to the chunks
*
#if !defined(GSI_MAP_TABLE_T)
typedef struct _GSIMapBucket GSIMapBucket_t;
typedef struct _GSIMapNode GSIMapNode_t;
typedef GSIMapBucket_t *GSIMapBucket;
typedef GSIMapNode_t *GSIMapNode;
#endif
struct _GSIMapNode {
GSIMapNode nextInBucket; /* Linked list of bucket. */
GSIMapKey key;
#if GSI_MAP_HAS_VALUE
GSIMapVal value;
#endif
};
struct _GSIMapBucket {
uintptr_t nodeCount; /* Number of nodes in bucket. */
GSIMapNode firstNode; /* The linked list of nodes. */
};
#if defined(GSI_MAP_TABLE_T)
typedef GSI_MAP_TABLE_T *GSIMapTable;
#else
typedef struct _GSIMapTable GSIMapTable_t;
typedef GSIMapTable_t *GSIMapTable;
struct _GSIMapTable {
NSZone *zone;
uintptr_t nodeCount; /* Number of used nodes in map. */
uintptr_t bucketCount; /* Number of buckets in map. */
GSIMapBucket buckets; /* Array of buckets. */
GSIMapNode freeNodes; /* List of unused nodes. */
uintptr_t chunkCount; /* Number of chunks in array. */
GSIMapNode *nodeChunks; /* Chunks of allocated memory. */
uintptr_t increment;
#ifdef GSI_MAP_EXTRA
GSI_MAP_EXTRA extra;
#endif
};
_GSIMapTable结构体内的变量理解:
1、buckets:存储着GSIMapBucket对象的数组,可以堪称是一个单向链表,每个GSIMapBucket中的firstNode->nextInBucket表示下一个bucket,依次连接。
2、bucketCount表示buckets的数量。
3、nodeChunks,表示一个数组指针,数组存储所有单链表的首个元素node。
4、chunkCount 表示数组大小。
5、freeNodes是需要释放的元素,是一个单向链表。
_GSIMapTable其实就是一个hash表结构,既可以以数组的形式取到每个单向链表首元素,也可以以链表形式取得。通过数组能够方便取到每个单向链表,再利用链表结构方便增删。
存储容器NCTbl
// 根容器,NSNotificationCenter持有
typedef struct NCTbl {
Observation *wildcard; /* 链表结构,保存既没有name也没有object的通知 */
GSIMapTable nameless; /* 存储没有name但是有object的通知 */
GSIMapTable named; /* 存储带有name的通知,不管有没有object */
...
} NCTable;
// Observation 存储观察者和响应结构体,基本的存储单元
typedef struct Obs {
id observer; /* 观察者,接收通知的对象 */
SEL selector; /* 响应方法 */
struct Obs *next; /* Next item in linked list. */
...
} Observation;
wildcard:Observation结构,存储既没有name也没有object的通知
nameless:GSIMapTable结构,存储存储没有name但是有object的通知
named:GSIMapTable,存储带有name的通知,不管有没有object的通知。
注册通知
selector: (SEL)selector注册通知
/*
observer:观察者,即通知的接收者
selector:接收到通知时的响应方法
name: 通知name
object:携带对象
*/
- (void) addObserver: (id)observer
selector: (SEL)selector
name: (NSString*)name
object: (id)object {
// 前置条件判断
......
// 创建一个observation对象,持有观察者和SEL,下面进行的所有逻辑就是为了存储它
o = obsNew(TABLE, selector, observer);
/*======= case1: 如果name存在 =======*/
if (name) {
//-------- NAMED是个宏,表示名为named字典。以name为key,从named表中获取对应的mapTable
n = GSIMapNodeForKey(NAMED, (GSIMapKey)(id)name);
if (n == 0) { // 不存在,则创建
m = mapNew(TABLE); // 先取缓存,如果缓存没有则新建一个map
GSIMapAddPair(NAMED, (GSIMapKey)(id)name, (GSIMapVal)(void*)m);
...
}
else { // 存在则把值取出来 赋值给m
m = (GSIMapTable)n->value.ptr;
}
//-------- 以object为key,从字典m中取出对应的value,其实value被MapNode的结构包装了一层,这里不追究细节
n = GSIMapNodeForSimpleKey(m, (GSIMapKey)object);
if (n == 0) {// 不存在,则创建
o->next = ENDOBS;
GSIMapAddPair(m, (GSIMapKey)object, (GSIMapVal)o);
}
else {
list = (Observation*)n->value.ptr;
o->next = list->next;
list->next = o;
}
}
/*======= case2:如果name为空,但object不为空 =======*/
else if (object) {
// 以object为key,从nameless字典中取出对应的value,value是个链表结构
n = GSIMapNodeForSimpleKey(NAMELESS, (GSIMapKey)object);
// 不存在则新建链表,并存到map中
if (n == 0) {
o->next = ENDOBS;
GSIMapAddPair(NAMELESS, (GSIMapKey)object, (GSIMapVal)o);
}
else { // 存在 则把值接到链表的节点上
...
}
}
/*======= case3:name 和 object 都为空 则存储到wildcard链表中 =======*/
else {
o->next = WILDCARD;
WILDCARD = o;
}
}
从上面介绍的存储容器中我们了解到NCTable结构体中核心的三个变量以及功能:wildcard、named、nameless,在源码中直接用宏定义表示了:WILDCARD、NAMELESS、NAMED。
case1: 存在name(无论object是否存在)
1、注册通知,如果通知的name存在,则以name为key从named字典中取出值n(这个n其实被MapNode包装了一层,便于理解这里直接认为没有包装),这个n还是个字典,各种判空新建逻辑不讨论。
2、然后以object为key,从字典n中取出对应的值,这个值就是Observation类型(后面简称obs)的链表,然后把刚开始创建的obs对象o存储进去。
数据结构关系图
如果注册通知时传入name,那么会是一个双层的存储结构
1、找到NCTable中的named表,这个表存储了还有name的通知
2、以name作为key,找到value,这个value依然是一个map
3、map的结构是以object作为key,obs对象为value,这个obs对象的结构上面已经解释,主要存储了observer & SEL
case2: 只存在object
1、以object为key,从nameless字典中取出value,此value是个obs类型的链表。
2、把创建的obs类型的对象o存储到链表中。
数据结构关系图
只存在object时存储只有一层,那就是object和obs对象之间的映射
case3: 没有name和object
这种情况直接把obs对象存放在了Observation *wildcard 链表结构中。
block - 注册通知
- (id) addObserverForName: (NSString *)name
object: (id)object
queue: (NSOperationQueue *)queue
usingBlock: (GSNotificationBlock)block
{
// 创建一个临时观察者
GSNotificationObserver *observer =
[[GSNotificationObserver alloc] initWithQueue: queue block: block];
// 调用了@selector的注册方法
[self addObserver: observer
selector: @selector(didReceiveNotification:)
name: name
object: object];
return observer;
}
- (void) didReceiveNotification: (NSNotification *)notif {
if (_queue != nil) {
GSNotificationBlockOperation *op = [[GSNotificationBlockOperation alloc]
initWithNotification: notif block: _block];
[_queue addOperation: op];
} else {
CALL_BLOCK(_block, notif);
}
}
这个接口依赖于selector注册,,只是多了一层代理观察者GSNotificationObserver,
1、创建一个GSNotificationObserver类型的对象observer,并把queue和block保存下来
2、调用接口1进行通知的注册
3、接收到通知时会响应observer的didReceiveNotification:方法,然后在didReceiveNotification:中把block抛给指定的queue去执行。
从上述介绍可以总结:
1、存储是以name和object为维度的,即判定是不是同一个通知要从name和object区分,如果他们都相同则认为是同一个通知,后面包括查找逻辑、删除逻辑都是以这两个为维度的,问题列表中的第九题也迎刃而解了。
2、理解数据结构的设计是整个通知机制的核心,其他功能只是在此基础上扩展了一些逻辑。
3、存储过程并没有做去重操作,这也解释了为什么同一个通知注册多次则响应多次。
发送通知
// 发送通知
- (void) postNotificationName: (NSString*)name
object: (id)object
userInfo: (NSDictionary*)info
{
// 构造一个GSNotification对象, GSNotification继承了NSNotification
GSNotification *notification;
notification = (id)NSAllocateObject(concrete, 0, NSDefaultMallocZone());
notification->_name = [name copyWithZone: [self zone]];
notification->_object = [object retain];
notification->_info = [info retain];
// 进行发送操作
[self _postAndRelease: notification];
}
//发送通知的核心函数,主要做了三件事:查找通知、发送、释放资源
- (void) _postAndRelease: (NSNotification*)notification {
//step1: 从named、nameless、wildcard表中查找对应的通知
...
//step2:执行发送,即调用performSelector执行响应方法,从这里可以看出是同步的
[o->observer performSelector: o->selector
withObject: notification];
//step3: 释放资源
RELEASE(notification);
}
上述代码注释说的很清晰了,主要做了三件事
1、通过name & object 查找到所有的obs对象(保存了observer和sel),放到数组中。
2、通过performSelector:逐一调用sel,这是个同步操作。
3、释放notification对象。发送过程的概述:
1、从三个存储容器中:named、nameless、wildcard去查找对应的obs对象。
2、然后通过performSelector:逐一调用响应方法,这就完成了发送流程。核心点:
1、同步发送
2、遍历所有列表,即注册多次通知就会响应多次
删除通知
1、查找时仍然以name和object为维度的,再加上observer做区分。
2、因为查找时做了这个链表的遍历,所以删除时会把重复的通知全都删除掉。
更多源码下载GNUStep
异步通知
入队
入队
下面为精简版的源码,看源码的注释,基本上能明白大致逻辑
1、根据coalesceMask参数判断是否合并通知。
2、接着根据postingStyle参数,判断通知发送的时机,
如果不是立即发送则把通知加入到队列中:_asapQueue、_idleQueue。
核心点:
1、队列是双向链表实现
2、当postingStyle值是立即发送时,调用的是NSNotificationCenter进行发送的,所以NSNotificationQueue还是依赖NSNotificationCenter进行发送
/*
* 把要发送的通知添加到队列,等待发送
* NSPostingStyle 和 coalesceMask在上面的类结构中有介绍
* modes这个就和runloop有关了,指的是runloop的mode
*/
- (void) enqueueNotification: (NSNotification*)notification
postingStyle: (NSPostingStyle)postingStyle
coalesceMask: (NSUInteger)coalesceMask
forModes: (NSArray*)modes
{
......
// 判断是否需要合并通知
if (coalesceMask != NSNotificationNoCoalescing) {
[self dequeueNotificationsMatching: notification
coalesceMask: coalesceMask];
}
switch (postingStyle) {
case NSPostNow: {
...
// 如果是立马发送,则调用NSNotificationCenter进行发送
[_center postNotification: notification];
break;
}
case NSPostASAP:
// 添加到_asapQueue队列,等待发送
add_to_queue(_asapQueue, notification, modes, _zone);
break;
case NSPostWhenIdle:
// 添加到_idleQueue队列,等待发送
add_to_queue(_idleQueue, notification, modes, _zone);
break;
}
}
发送通知
这里截取了发送通知的核心代码,这个发送通知逻辑如下:
1、runloop触发某个时机,调用GSPrivateNotifyASAP()和GSPrivateNotifyIdle()方法,这两个方法最终都调用了notify()方法。
2、notify()所做的事情就是调用NSNotificationCenter的postNotification:进行发送通知。
static void notify(NSNotificationCenter *center,
NSNotificationQueueList *list,
NSString *mode, NSZone *zone)
{
......
// 循环遍历发送通知
for (pos = 0; pos < len; pos++)
{
NSNotification *n = (NSNotification*)ptr[pos];
[center postNotification: n];
RELEASE(n);
}
......
}
// 发送_asapQueue中的通知
void GSPrivateNotifyASAP(NSString *mode)
{
notify(item->queue->_center,
item->queue->_asapQueue,
mode,
item->queue->_zone);
}
// 发送_idleQueue中的通知
void GSPrivateNotifyIdle(NSString *mode)
{
notify(item->queue->_center,
item->queue->_idleQueue,
mode,
item->queue->_zone);
}
NSNotificationQueue总结:
1、依赖runloop,所以如果在其他子线程使用NSNotificationQueue,需要开启runloop。
2、最终还是通过NSNotificationCenter进行发送通知,所以这个角度讲它还是同步的。
3、所谓异步,指的是非实时发送而是在合适的时机发送,并没有开启异步线程。
主线程响应通知
异步线程发送通知则响应函数也是在异步线程,如果执行UI刷新相关的话就会出问题,那么如何保证在主线程响应通知呢?
其实也是比较常见的问题了,基本上解决方式如下几种:
1、使用addObserverForName: object: queue: usingBlock方法注册通知,指定在mainqueue上响应block。
2、在主线程注册一个machPort,它是用来做线程通信的,当在异步线程收到通知,然后给machPort发送消息,这样肯定是在主线程处理的。
问题列表
1、通知的实现原理(结构设计、通知如何存储的、name&observer&SEL之间的关系等)
通知里面主要有三个类NSNotification通知对象,包括name,object,userinfo
NSNotificationCenter,通知中心,负责添加、发送、移除通知。
NSNotificationQueue,通知队列,负责某些时机触发调用通知,最后调用还是NSNotificationCenter通知中心 post通知。
通知队列里的异步,实际上不是真正的异步,更多是延时发送,利用了runloop的时机来触发。
根据开源代码GNUStep推测,通知时结构体,通过双向链表进行数据存储
// 根容器,NSNotificationCenter持有
typedef struct NCTbl {
Observation *wildcard; /* 链表结构,保存既没有name也没有object的通知 */
GSIMapTable nameless; /* 存储没有name但是有object的通知 */
GSIMapTable named; /* 存储带有name的通知,不管有没有object */
...
} NCTable;
// Observation 存储观察者和响应结构体,基本的存储单元
typedef struct Obs {
id observer; /* 观察者,接收通知的对象 */
SEL selector; /* 响应方法 */
struct Obs *next; /* Next item in linked list. */
...
} Observation;
通知是以key value的形式存储,
需要重点强调:
通知以 name和object两个纬度来存储相关通知内容,也就是我们添加通知的时候传入的两个不同的方法.
name&observer&SEL之间的关系:name作为key, observer作为观察者对象,当合适时机触发就会调用observer的SEL
2、通知的发送时同步的,还是异步的
同步发送,因为要调用消息转发.
所谓异步,指的是非实时发送而是在合适的时机发送,并没有开启异步线程.
3、NSNotificationCenter 接受消息和发送消息是在一个线程里吗?如何异步发送消息
是的, 异步线程发送通知则响应函数也是在异步线程.
异步发送通知可以开启异步线程发送即可.
4、NSNotificationQueue是异步还是同步发送?在哪个线程响应?
// 表示通知的发送时机
typedef NS_ENUM(NSUInteger, NSPostingStyle) {
NSPostWhenIdle = 1, // runloop空闲时发送通知
NSPostASAP = 2, // 尽快发送,这种时机是穿插在每次事件完成期间来做的
NSPostNow = 3 // 立刻发送或者合并通知完成之后发送
};
NSPostWhenIdle:异步发送
NSPostASAP:异步发送
NSPostNow:同步发送NSNotificationCenter都是同步发送的,
而关于NSNotificationQueue的异步发送,从线程的角度看并不是真正的异步发送,或可称为延时发送,它是利用了runloop的时机来触发的。
异步线程发送通知则响应函数也是在异步线程,主线程发送则在主线程。
5、NSNotificationQueue和runloop的关系
NSNotificationQueue依赖runloop. 因为通知队列要在runloop回调的某个时机调用通知中心发送通知。
6、如何保证通知接收的线程在主线程
两种方式:
1、系统接受通知的API指定队列
2、NSMachPort的方式 通过在主线程的 runloop 中添加 machPort,设置这个 port 的 delegate,通过这个 Port 其他线程可以跟主线程通信,在这个 port 的代理回调中执行的代码肯定在主线程中运行,所以,在这里调用 NSNotificationCenter 发送通知即可
7、页面销毁时不移除通知会崩溃吗?
iOS9.0之前,会crash,原因:通知中心对观察者的引用是 unsafe_unretained,导致当观察者释放的时候,观察者的指针值并不为nil,出现野指针.
iOS9.0之后,不会crash,原因:通知中心对观察者的引用是 weak。
8、多次添加同一个通知会是什么结果?多次移除通知呢
多次添加同一个通知,会导致发送一次这个通知的时候,响应多次通知回调。
多次移除通知不会产生crash。
9、下面的方式能接收到通知吗?为什么
// 发送通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification:) name:@"TestNotification" object:@1];
// 接收通知
[NSNotificationCenter.defaultCenter postNotificationName:@"TestNotification" object:nil];
不能。根据推测的通知中心存储通知观察者的结构。
// 根容器,NSNotificationCenter持有
typedef struct NCTbl {
Observation *wildcard; /* 链表结构,保存既没有name也没有object的通知 */
GSIMapTable nameless; /* 存储没有name但是有object的通知 */
GSIMapTable named; /* 存储带有name的通知,不管有没有object */
...
} NCTable;
当添加通知监听的时候,我们传入了name和object,所以,观察者的存储链表是这样的:named表:key(name) : value->key(object) : value(Observation)
因此在发送通知的时候,如果只传入name而并没有传入object,是找不到Observation的,也就不能执行观察者回调。