一.模型结构

1.NSNotification

@interface NSNotification : NSObject <NSCopying, NSCoding>
// 告诉的称号
@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 API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0)) NS_DESIGNATED_INITIALIZER;
- (nullable instancetype)initWithCoder:(NSCoder *)coder NS_DESIGNATED_INITIALIZER;
@end
@interface NSNotification (NSNotificationCreation)
// 创立一个告诉
+ (instancetype)notificationWithName:(NSNotificationName)aName object:(nullable id)anObject;
// 创立一个告诉
+ (instancetype)notificationWithName:(NSNotificationName)aName object:(nullable id)anObject userInfo:(nullable NSDictionary *)aUserInfo;
- (instancetype)init /*API_UNAVAILABLE(macos, ios, watchos, tvos)*/;	/* do not invoke; not a valid initializer for this class */
@end

接纳告诉时会回来这个目标

2.NSNotificationCenter

@interface NSNotificationCenter : NSObject {
    @package
    void *_impl;
    void *_callback;
    void *_pad[11];
}
// 默许的告诉中心,大局唯一
@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;
// 在告诉中心注册一个观察者,block回调的办法替代selector
- (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.
@end

是一个单例类,担任管理告诉的创立和发送,首要做三件事

  • 注册告诉
  • 发送告诉
  • 移除告诉

注册告诉目前有两种办法:selectorblock

//注册观察者
- (void)addObserver:(id)observer selector:(SEL)aSelector name:(nullable NSNotificationName)aName object:(nullable id)anObject;
- (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));

关于增加指定观察者目标的办法,observer不能为nilblock办法会履行copy办法,回来的是运用的匿名观察者目标,且指定观察者处理音讯的操作目标NSOperationQueue

关于指定的音讯称号name及发送者目标object都能够为空,即接纳一切音讯及一切发送目标发送的音讯;若指定其中之一或许都指定,则表明接纳指定音讯称号及发送者的音讯;

关于block办法指定的queue行列可为nil,则默许在发送音讯线程处理;若指定主行列,即主线程处理,避免履行UI操作导致反常;

注意:注册观察者告诉音讯应避免重复注册,会导致重复处理告诉音讯,且block对持有外部目标,因而需求避免引发循环引证问题;

发送告诉

//发送音讯
- (void)postNotification:(NSNotification *)notification;
- (void)postNotificationName:(NSNotificationName)aName object:(nullable id)anObject;
- (void)postNotificationName:(NSNotificationName)aName object:(nullable id)anObject userInfo:(nullable NSDictionary *)aUserInfo;

能够经过NSNotification包装的告诉音讯目标发送音讯,也能够分别指定音讯称号、发送者及带着的信息来发送,且为同步履行模式,需求等候一切注册的观察者处理完结该告诉音讯,办法才会回来持续往下履行,且关于block办法处理告诉目标是在注册音讯指定的行列中履行,关于非block办法是在同一线程处理。

注意:音讯发送类型需求与注册时类型一致,即若注册观察者一起指定了音讯称号及发送者,则发送音讯也需求一起指定,否则无法接纳到音讯

移除告诉

//移除观察者
- (void)removeObserver:(id)observer;
- (void)removeObserver:(id)observer name:(nullable NSNotificationName)aName object:(nullable id)anObject;

可移除指定的观察者一切告诉音讯,即该观察者不再接纳任何音讯,一般用于观察者目标dealloc开释后调用,但在ios9macos10.11之后不需求手动调用,dealloc现已主动处理;

3.NSNotificationQueue

@interface NSNotificationQueue : NSObject {
@private
    id		_notificationCenter;
    id		_asapQueue;
    id		_asapObs;
    id		_idleQueue;
    id		_idleObs;
}
@property (class, readonly, strong) NSNotificationQueue *defaultQueue;
- (instancetype)initWithNotificationCenter:(NSNotificationCenter *)notificationCenter NS_DESIGNATED_INITIALIZER;
// 把告诉增加到行列中
- (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;
@end

能够经过defaultQueue获取当时线程绑定的告诉音讯行列,也能够经过initWithNotificationCenter:来指定告诉管理中心

该目标首要做两件事

  1. 增加告诉到行列
  2. 删去告诉

告诉发送机遇

// 告诉的发送机遇
typedef NS_ENUM(NSUInteger, NSPostingStyle) {
    NSPostWhenIdle = 1, // runloop空闲时发送告诉
    NSPostASAP = 2,     // 在当时告诉调用或许计时器完毕发出告诉
    NSPostNow = 3       // 马上发送或在兼并告诉完结之后发送
};

告诉兼并策略

// 告诉兼并的策略,有些时分同名告诉只想存在一个,这时分就能够用到它了
typedef NS_OPTIONS(NSUInteger, NSNotificationCoalescing) {
    NSNotificationNoCoalescing = 0,// 默许不兼并
    NSNotificationCoalescingOnName = 1,// 依照告诉名字兼并告诉
    NSNotificationCoalescingOnSender = 2// 依照传入的object兼并告诉
};

异步告诉的运用

NSNotification *noti = [NSNotification notificationWithName:@"111" object:nil];
[[NSNotificationQueue defaultQueue] enqueueNotification:noti postingStyle:NSPostASAP];

告诉兼并的运用

// 发送多个告诉
NSNotification *noti = [NSNotification notificationWithName:@"NSNotification" object:nil];
[[NSNotificationQueue defaultQueue] enqueueNotification:noti postingStyle:NSPostASAP coalesceMask:NSNotificationNoCoalescing forModes:nil];
[[NSNotificationQueue defaultQueue] enqueueNotification:noti postingStyle:NSPostWhenIdle coalesceMask:NSNotificationNoCoalescing forModes:nil];
[[NSNotificationQueue defaultQueue] enqueueNotification:noti postingStyle:NSPostNow coalesceMask:NSNotificationNoCoalescing forModes:nil];
// 注册名为NSNotification的告诉
[[NSNotificationCenter defaultCenter] addObserver:self selector:*@selector(noti:) name:@"NSNotification" object:nil];
- (void) noti:(NSNotification *) noti {
  NSLog(@"noti");
}

coalesceMask 设置为 NSNotificationNoCoalescing 成果打印了三个noti 当 coalesceMask 设置为 NSNotificationCoalescingOnName 成果打印了一个noti

4.GSNotificationObserver

@implementation GSNotificationObserver {
    NSOperationQueue *_queue; // 保存传入的行列
    GSNotificationBlock _block; // 保存传入的block
}
- (id) initWithQueue: (NSOperationQueue *)queue 
               block: (GSNotificationBlock)block {
    ......初始化操作
}
- (void) dealloc {
    ....
}
// 呼应接纳告诉的办法,并在指定行列中履行block
- (void) didReceiveNotification: (NSNotification *)notif {
    if (_queue != nil){
            GSNotificationBlockOperation *op = [[GSNotificationBlockOperation alloc] 
                    initWithNotification: notif block: _block];
            [_queue addOperation: op];
    } else {
        CALL_BLOCK(_block, notif);
    }
}
@end

这个类是GNUStep源码中界说的,它的作用是署理观察者,首要用来完结接口:addObserverForName:object: queue: usingBlock:时用到,即要完结在指定行列回调block,那么GSNotificationObserver目标保存了queueblock信息,而且作为观察者注册到告诉中心,等到接纳告诉时触发了呼应办法,并在呼应办法中把block抛到指定queue中履行

二.底层剖析

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.从bucket的视点,当作一个单向链表

  • buckets是一个单向链表,存储着GSIMapBucketGSIMapBucket中其firstNode->nextInBucket表明下一个bucketfirstNode表明另一条单链表的首个元素。
  • bucketCount表明buckets的数量

2.从chunk视点,当作一个数组指针

  • nodeChunks表明一个数组指针,数组存储一切单链表的首个元素node
  • chunkCount表明数组大小

此外freeNodes则便是需求开释的元素,是一个单向链表。
其实便是一个hash表结构,既能够以数组的办法取到每个单向链表首元素,也能够以链表办法获得。
经过数组能够便利取到每个单向链表,再利用链表结构便利增删。

//取单向链表
//经过hash值%最大个数 来获取index,然后取出单向链表,再进行链表增删
GS_STATIC_INLINE GSIMapBucket
GSIMapPickBucket(unsigned hash, GSIMapBucket buckets, uintptr_t bucketCount) {
  return buckets + hash % bucketCount;
}
GS_STATIC_INLINE GSIMapBucket
GSIMapBucketForKey(GSIMapTable map, GSIMapKey key) {
  return GSIMapPickBucket(GSI_MAP_HASH(map, key),
    map->buckets, map->bucketCount);
}
//增删元素
GS_STATIC_INLINE void
GSIMapLinkNodeIntoBucket(GSIMapBucket bucket, GSIMapNode node) {
  node->nextInBucket = bucket->firstNode;
  bucket->firstNode = node;
}
GS_STATIC_INLINE void
GSIMapUnlinkNodeFromBucket(GSIMapBucket bucket, GSIMapNode node) {
  if (node == bucket->firstNode) {
      bucket->firstNode = node->nextInBucket;
  } else {
      GSIMapNode tmp = bucket->firstNode;
      while (tmp->nextInBucket != node) {
	  tmp = tmp->nextInBucket;
	}
      tmp->nextInBucket = node->nextInBucket;
    }
  node->nextInBucket = 0;
}

这是OC中完结hash表的一种办法。但关于Javahashmap来说,更为简单了。hashmap触及红黑树等查找问题,后续贴出对比下。

2.存储容器NCTbl

告诉大局目标表结构

// 根容器,NSNotificationCenter持有
typedef struct NCTbl {
    Observation		*wildcard;	/* 链表结构,保存既没有name也没有object的告诉*/
    GSIMapTable		nameless;	/* 存储没有name但是有object的告诉*/
    GSIMapTable		named;		/* 存储带有name的告诉,不管有没有object*/
    unsigned		lockCount;	/* Count recursive operations.	*/
    NSRecursiveLock	*_lock;		/* Lock out other threads.	*/
    Observation		*freeList;
    Observation		**chunks;
    unsigned		numChunks;
    GSIMapTable		cache[CACHESIZE];
    unsigned short	chunkIndex;
    unsigned short	cacheIndex;
} NCTable;
// Observation 存储观察者和呼应结构体,根本的存储单元
typedef struct Obs { 
    id observer;      /* 观察者,接纳告诉的目标 */ 
    SEL selector;     /* 呼应办法 */ 
    struct Obs *next; /* Next item in linked list. */ 
    ... 
} Observation;

保存含有告诉称号的告诉表named需求注册object目标,因而该表结构体经过传入的name作为key,其中value一起也为GSIMapTable表用于存储对应的object目标的observer目标;

对没有传入告诉称号只传入object目标的告诉表nameless而言,只需求保存objectobserver的对应联系,因而object作为keyobserver作为value

3.注册告诉

中心源码- 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结构体中中心的三个变量以及功用:wildcardnamednameless,在源码中直接用宏界说表明了:WILDCARDNAMELESSNAMED

case1: 存在name(不管object是否存在)

  1. 注册告诉,假如告诉的name存在,则以name为key从named字典中取出值n(这个n其实被MapNode包装了一层,便于理解这儿直接以为没有包装),这个n仍是个字典,各种判空新建逻辑不讨论
  2. 然后以object为key,从字典n中取出对应的值,这个值便是Observation类型(后面简称obs)的链表,然后把刚开始创立的obs目标o存储进去

数据结构联系图:

从底层了解面试题-NSNotification篇

假如注册告诉时传入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存储到链表中

数据结构联系图:

从底层了解面试题-NSNotification篇

只存在object时存储只要一层,那便是objectobs目标之间的映射

case3: 没有name和object

这种情况直接把obs目标存放在了Observation *wildcard 链表结构中

中心源码-block办法

block办法仅仅 Selector 函数的包装

- (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;
}
- (id) initWithQueue: (NSOperationQueue *)queue 
               block: (GSNotificationBlock)block {
    self = [super init];
    if (self == nil)
        return nil;
    ASSIGN(_queue, queue);
    _block = Block_copy(block);
    return self;
}
- (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,并把queueblock保存下来
  2. 调用接口1进行告诉的注册
  3. 接纳到告诉时会呼应observerdidReceiveNotification:办法,然后在didReceiveNotification:中把block抛给指定的queue去履行

4.发送告诉

中心代码

// 发送告诉
- (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目标(保存了observersel),放到数组中
  2. 经过performSelector:逐个调用sel,这是个同步操作
  3. 开释notification目标

源码逻辑能够看出发送过程的概述

  1. 从三个存储容器中:namednamelesswildcard去查找对应的obs目标
  2. 然后经过performSelector:逐个调用呼应办法,这就完结了发送流程

5.删去告诉

  1. 查找时仍然以nameobject为维度的,再加上observer做区别
  2. 由于查找时做了这个链表的遍历,所以删去时会把重复的告诉全都删去掉
// 删去现已注册的告诉
- (void) removeObserver: (id)observer
		   name: (NSString*)name
                 object: (id)object {
  if (name == nil && object == nil && observer == nil)
      return;
      ...
}
- (void) removeObserver: (id)observer{
  if (observer == nil)
      return;
  [self removeObserver: observer name: nil object: nil];
}

6.异步告诉

NSNotificationQueue的异步发送,从线程的视点看并不是真正的异步发送,或可称为延时发送,它是利用了runloop的机遇来触发的

逻辑

  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;
    }
}

异步发送告诉

  • runloop触发某个机遇,调用GSPrivateNotifyASAP()GSPrivateNotifyIdle()办法,这两个办法最终都调用了notify()办法

  • notify()所做的工作便是调用NSNotificationCenterpostNotification:进行发送告诉

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
 // 代码
@interface A : NSObject <NSMachPortDelegate>
- (void)test;
@end
@implementation A
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)test {
    [[NSNotificationCenter defaultCenter] addObserverForName:@"111" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        NSLog(@"current thread %@ 改写UI", [NSThread currentThread]);
        // 改写UI ...
    }];
}
@end
// 输出
current thread <NSThread: 0x7bf29110>{number = 3, name = (null)}
2017-02-27 11:53:46.531 notification[29510:12833116] current thread <NSThread: 0x7be1d6f0>{number = 1, name = main} 改写UI
  1. 在主线程注册一个machPort,它是用来做线程通信的,当在异步线程收到告诉,然后给machPort发送音讯,这样肯定是在主线程处理的,详细用法
// 代码
#import <CoreFoundation/CFRunLoop.h>
@interface A : NSObject <NSMachPortDelegate>
@property NSMutableArray *notifications;
@property NSThread *notificationThread;
@property NSLock *notificationLock;
@property NSMachPort *notificationPort;
- (void)setUpThreadingSupport;
- (void)handleMachMessage:(void *)msg;
- (void)processNotification:(NSNotification *)notification;
- (void)test;
@end
@implementation A
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)test {
    [self setUpThreadingSupport];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(processNotification:) name:@"111" object:nil];
}
- (void)setUpThreadingSupport {
    if (self.notifications) {
        return;
    }
    self.notifications      = [[NSMutableArray alloc] init];
    self.notificationLock   = [[NSLock alloc] init];
    self.notificationThread = [NSThread mainThread];
    self.notificationPort = [[NSMachPort alloc] init];
    [self.notificationPort setDelegate:self];
    [[NSRunLoop currentRunLoop] addPort:self.notificationPort
                                forMode:(NSString *)kCFRunLoopCommonModes];
}
- (void)handleMachMessage:(void *)msg {
    [self.notificationLock lock];
    while ([self.notifications count]) {
        NSNotification *notification = [self.notifications objectAtIndex:0];
        [self.notifications removeObjectAtIndex:0];
        [self.notificationLock unlock];
        [self processNotification:notification];
        [self.notificationLock lock];
    };
    [self.notificationLock unlock];
}
- (void)processNotification:(NSNotification *)notification {
    if ([NSThread currentThread] != self.notificationThread) {
        [self.notificationLock lock];
        [self.notifications addObject:notification];
        [self.notificationLock unlock];
        [self.notificationPort sendBeforeDate:[NSDate date]
                                   components:nil
                                         from:nil
                                     reserved:0];
    } else {
        NSLog(@"current thread %@ 改写UI", [NSThread currentThread]);
        // 改写UI ...
    }
}
@end
// 输出
2017-02-27 11:49:04.296 notification[29036:12827315] current thread <NSThread: 0x7be3e000>{number = 3, name = (null)}
2017-02-27 11:49:04.307 notification[29036:12827268] current thread <NSThread: 0x7bf3b970>{number = 1, name = main} 改写UI

三.问题

1.observer 的目标存储在何处?

// NSNotificationCenter的init办法
- (id) init {
  if ((self = [super init]) != nil) {
      _table = newNCTable();
    }
  return self;
}

每个 NSNotificationCenter 都有一个默许的 _table。其对 observer 进行引证(iOS9曾经 unsafe_unretained,iOS9今后 weak)。

2.post 的时分依据何种办法查找承受告诉的目标?

仔细看一看【中心源码-Selector办法
table 中查找 observer object 的时分,首先依据的是 object,接下来依据的是 name,可见 name 的优先级比较

3.体系的告诉 Name 有哪些?

// 当程序被推送到后台时
UIKIT_EXTERN NSNotificationName const UIApplicationDidEnterBackgroundNotification       NS_AVAILABLE_IOS(4_0);
// 当程序从后台即将重新回到前台时
UIKIT_EXTERN NSNotificationName const UIApplicationWillEnterForegroundNotification      NS_AVAILABLE_IOS(4_0);
// 当程序完结载入后告诉
UIKIT_EXTERN NSNotificationName const UIApplicationDidFinishLaunchingNotification;
// 应用程序转为激活状况时
UIKIT_EXTERN NSNotificationName const UIApplicationDidBecomeActiveNotification;
// 用户按下主屏幕按钮调用告诉,并未进入后台状况
UIKIT_EXTERN NSNotificationName const UIApplicationWillResignActiveNotification;
// 内存较低时告诉
UIKIT_EXTERN NSNotificationName const UIApplicationDidReceiveMemoryWarningNotification;
// 当程序即将退出时告诉
UIKIT_EXTERN NSNotificationName const UIApplicationWillTerminateNotification;
// 当体系时刻产生改动时告诉
UIKIT_EXTERN NSNotificationName const UIApplicationSignificantTimeChangeNotification;
// 当StatusBar框方向即将变化时告诉
UIKIT_EXTERN NSNotificationName const UIApplicationWillChangeStatusBarOrientationNotification __TVOS_PROHIBITED; // userInfo contains NSNumber with new orientation
// 当StatusBar框方向改动时告诉
UIKIT_EXTERN NSNotificationName const UIApplicationDidChangeStatusBarOrientationNotification __TVOS_PROHIBITED;  // userInfo contains NSNumber with old orientation
// 当StatusBar框Frame即将改动时告诉
UIKIT_EXTERN NSNotificationName const UIApplicationWillChangeStatusBarFrameNotification __TVOS_PROHIBITED;       // userInfo contains NSValue with new frame
// 当StatusBar框Frame改动时告诉
UIKIT_EXTERN NSNotificationName const UIApplicationDidChangeStatusBarFrameNotification __TVOS_PROHIBITED;        // userInfo contains NSValue with old frame
// 后台下载状况产生改动时告诉(iOS7.0今后可用)
UIKIT_EXTERN NSNotificationName const UIApplicationBackgroundRefreshStatusDidChangeNotification NS_AVAILABLE_IOS(7_0) __TVOS_PROHIBITED;
// 受保护的文件当时变为不可用时告诉
UIKIT_EXTERN NSNotificationName const UIApplicationProtectedDataWillBecomeUnavailable    NS_AVAILABLE_IOS(4_0);
// 受保护的文件当时变为可用时告诉
UIKIT_EXTERN NSNotificationName const UIApplicationProtectedDataDidBecomeAvailable       NS_AVAILABLE_IOS(4_0);
// 截屏告诉(iOS7.0今后可用)
UIKIT_EXTERN NSNotificationName const UIApplicationUserDidTakeScreenshotNotification NS_AVAILABLE_IOS(7_0);

四.面试题

1.告诉的完结原理(结构设计、告诉怎么存储的、name&observer&SEL之间的联系等)

告诉中心结构大概分为如下几个类

  • NSNotification 告诉的模型 name、object、userinfo.
  • NSNotificationCenter告诉中心 担任发送NSNotification
  • NSNotificationQueue告诉行列 担任在某些机遇触发 调用NSNotificationCenter告诉中心 post告诉

告诉是结构体经过双向链表进行数据存储

// 根容器,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;

首要是以keyvalue的办法存储,这儿需求重点着重一下 告诉以nameobject两个纬度来存储相关告诉内容,也便是我们增加告诉的时分传入的两个不同的办法.

name&observer&SEL之间的联系
name作为key,observer作为观察者目标,当适宜机遇触发就会调用observerSEL

2.告诉的发送时同步的,仍是异步的

同步发送,由于要调用音讯转发.
所谓异步,指的是非实时发送而是在适宜的机遇发送,并没有敞开异步线程.

3.NSNotificationCenter 承受音讯和发送音讯是在一个线程里吗?怎么异步发送音讯

是的, 异步线程发送告诉则呼应函数也是在异步线程.
异步发送告诉能够敞开异步线程发送即可.

4.NSNotificationQueue是异步仍是同步发送?在哪个线程呼应?

// 表明告诉的发送机遇
typedef NS_ENUM(NSUInteger, NSPostingStyle) {
    NSPostWhenIdle = 1, // runloop空闲时发送告诉
    NSPostASAP = 2, // 赶快发送,这种机遇是穿插在每次事情完结期间来做的
    NSPostNow = 3 // 马上发送或许兼并告诉完结之后发送
};
. NSPostWhenIdle NSPostASAP NSPostNow
NSPostingStyle 异步发送 异步发送 同步发送

NSNotificationCenter都是同步发送的,而这儿介绍关于NSNotificationQueue的异步发送,从线程的视点看并不是真正的异步发送,或可称为延时发送,它是利用了runloop的机遇来触发的.

异步线程发送告诉则呼应函数也是在异步线程,主线程发送则在主线程.

5.NSNotificationQueue和runloop的联系

NSNotificationQueue依靠runloop. 由于告诉行列要在runloop回调的某个机遇调用告诉中心发送告诉.从下面的枚举值就能看出来

// 表明告诉的发送机遇
typedef NS_ENUM(NSUInteger, NSPostingStyle) {
    NSPostWhenIdle = 1, // runloop空闲时发送告诉
    NSPostASAP = 2, // 赶快发送,这种机遇是穿插在每次事情完结期间来做的
    NSPostNow = 3 // 马上发送或许兼并告诉完结之后发送
};

6.怎么保证告诉接纳的线程在主线程

假如想在主线程呼应异步告诉的话能够用如下两种办法

  1. 体系承受告诉的API指定行列
  2. NSMachPort的办法 经过在主线程的 runloop 中增加 machPort,设置这个 portdelegate,经过这个 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;

当增加告诉监听的时分,我们传入了nameobject,所以,观察者的存储链表是这样的:
named表:key(name) : value->key(object) : value(Observation)

因而在发送告诉的时分,假如只传入name而并没有传入object,是找不到Observation的,也就不能履行观察者回调.